使用 sed 根据 OSX 中的内容重命名文件 [英] using sed to rename files based on contents in OSX

查看:56
本文介绍了使用 sed 根据 OSX 中的内容重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 OSX,我试图在 .Rnw 文件中提取一段文本,然后重命名该文件.

I'm using OSX, and I'm trying to take a piece of text within a .Rnw file, and then rename that file.

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

The file (text file) looks like this:

\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".

I want to grab the text in the \exname{} field, and make it the new title of the file. So, I want the file here to contain the contents as posted, and the whole file should be named "target.Rnw".

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

The link below got me started, but I can't make it work, such that the script takes the base file, then renames it based on that which is in the \exname{} field.

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

推荐答案

看看这是否有效:

$ 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

这篇关于使用 sed 根据 OSX 中的内容重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆