【问题标题】:using sed to rename files based on contents in OSX使用 sed 根据 OSX 中的内容重命名文件
【发布时间】:2018-04-13 15:03:17
【问题描述】:

我正在使用 OSX,我试图在 .Rnw 文件中获取一段文本,然后重命名该文件。

文件(文本文件)如下所示:

\begin{question}


A business incurs the following costs per unit: Labor  \$125/unit; Materials \$45/unit and rent  \$250,000/month. If the firm produces 1,000,000 units a month, the total variable costs equal
\begin{answerlist} 
\item \$125Million

\item \$45Million

\item \$1Million

\item \$170Million


\end{answerlist}
\end{question}

\begin{solution}
\begin{answerlist}
\item F. 
\item F. 
\item F. 
\item F. 
\end{answerlist}
\end{solution}

\exname{target}
\extype{schoice}
\exsolution{0001}
\exshuffle{TRUE}

我想获取 \exname{} 字段中的文本,并将其设置为文件的新标题。所以,我希望这里的文件包含发布的内容,整个文件应该命名为“target.Rnw”。

下面的链接让我开始了,但我不能让它工作,这样脚本会获取基本文件,然后根据 \exname{} 字段中的内容重命名它。

https://unix.stackexchange.com/questions/158447/grep-search-expression-and-rename-file

【问题讨论】:

    标签: sed


    【解决方案1】:

    看看这是否有效:

    $ cat ip.Rnw
    \end{solution}
    
    \exname{target}
    \extype{schoice}
    \exsolution{0001}
    \exshuffle{TRUE}
    
    $ # use { or } as delimiters
    $ # print second field if first field is \exname
    $ awk -F'[{}]' '$1=="\\exname"{print $2}' ip.Rnw
    target
    
    $ # with sed, use capture group and backreference
    $ sed -n 's/^\\exname{\(.*\)}/\1/p' ip.Rnw 
    target
    
    $ # echo is for testing purpose, remove it once things seem fine
    $ echo mv ip.Rnw "$(awk -F'[{}]' '$1=="\\exname"{print $2 ".Rnw"}' ip.Rnw)"
    mv ip.Rnw target.Rnw
    

    【讨论】:

    • 这太棒了。现在,我只需要实现这个循环。如果我有很多这样的文件,ip.Rnw, ip2.Rnw, ip3.Rnw, ip4.Rnw, . . . . ip300.Rnw 在单个目录中,我想通过所有文件自动运行此脚本。您能帮我了解如何循环处理所有文件吗?
    猜你喜欢
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多