Issue
So, imagine I have a whole bunch of files like so:
a line of text
% !TEX TS-parameter = ../
a line of text
a line of text
a line of text
\gresetgregpath{{music/}}
a line of text
a line of text
I need to copy the relative path ../
from the line where it appears near the top of the file into the spot between \gresetgregpath{{
and music/}}
later in the file:
a line of text
% !TEX TS-parameter = ../
a line of text
a line of text
a line of text
\\gresetgregpath{{../music/}}
a line of text
a line of text
The relative path differs from file to file, but % !TEX TS-parameter =
will always precede it and it will always be terminated by an end of line. % !TEX TS-parameter =
does not occur on any other line. The line that defines the destination (\gresetgregpath{{music/}
) is identical in all files and is guaranteed to appear only once in each file. The lines represented by a line of text
are otherwise arbitrary in both number and contents.
Given that I have a huge number of files to do this on, I'd like to do it in bulk with something like sed or awk. So how to I copy some text from one line and put it into the same file in a specific location on another line latter in the same file?
I have not tried anything myself at this point because I've only used sed for single line operations and have never used awk.
Solution
Best I can tell this should work for any characters in your input or search strings (if any of them can contain '
then use '\''
to represent that in the string definition) as its only doing literal string operations:
$ cat tst.sh
#!/usr/bin/env bash
srcMrkr='% !TEX TS-parameter = ' \
dstMrkr='\gresetgregpath{{music/}}' \
dstOfmt='\gresetgregpath{{%smusic/}}' \
awk '
index($0,ENVIRON["srcMrkr"]) == 1 {
info = substr($0,length(ENVIRON["srcMrkr"])+1)
}
$0 == ENVIRON["dstMrkr"] {
$0 = sprintf(ENVIRON["dstOfmt"],info)
}
{ print }
' file
$ ./tst.sh
a line of text
% !TEX TS-parameter = ../
a line of text
a line of text
a line of text
\gresetgregpath{{../music/}}
a line of text
a line of text
See How do I find the text that matches a pattern? and Is it possible to escape regex metacharacters reliably with sed for issues related to metacharacters and substrings during "pattern" matching and replacement.
Answered By - Ed Morton Answer Checked By - Gilberto Lyons (WPSolving Admin)