Reputation: 1853
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}
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".
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
Upvotes: 0
Views: 67
Reputation: 23677
See if this works:
$ 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
Upvotes: 2