Reputation: 1469
Im trying to write a bash script that will read whole file line by line, look for specific line, if that line exist - extract string from it into variable and search for another specific line and replace it with this variable. It has to be in while loop as there can be multiple occurances of these pair of lines hence I do not want to replace all lines with 1 variable as every case will be different, here is an example:
line1
mynumber: 666
line3
line4
show (value)
line5
line6
mynumber: 111
line7
line8
line9
line10
show (value)
so I want it to look like this after replacement:
line1
mynumber: 666
line3
line4
show (666,value)
line5
line6
mynumber: 111
line7
line8
line9
line10
show (111,value)
here is my broken code, that fails because variables are being picked up but added 1 after another (array) and I think this is breaking sed.
for i in $(seq $count);
do while IFS= read -r line;
do var1="$(grep -o -E '.{0,0}mynumber: .{0,3}' File.cs | egrep -o ".{3}$")" ; done < "$input";
sed -i "s/(value)/(${var1},value)/g
" File.cs; ; done
Issues im getting: Var= 666 111 and I would like to be only 1 value per replacement and Im getting error from sed: sed -e expression #1 : unterminated `s' command
Upvotes: 1
Views: 284
Reputation: 50795
AWK can do that single-handedly.
$ awk '$1=="mynumber:"{c=$2} $1=="show"{sub(/\(/,"&"c",")}1' file
line1
mynumber: 666
line3
line4
show (666,value)
line5
line6
mynumber: 111
line7
line8
line9
line10
show (111,value)
Upvotes: 3
Reputation: 5665
Perl solution:
perl -pe '$n=$1 if /mynumber: (\d+)/; s/show \(/show($n,/' file
Use -p
to loop over the input file line by line. (like sed or awk)
Set $n
to the first match group in /mynumber: (\d+)/
if there is a match.
Then, use s///
replacement to insert "$n,"
after "show("
Upvotes: -1
Reputation: 58483
This might work for you (GNU sed & parallel):
parallel -q sed -Ei '/{}/{h;:a;n;/^show/!ba;G;s/\((.*)\n.* (.*)/(\2,\1/}' file ::: 666 111
Use parallel to loop through the numbers 666
and 111
and sed to insert then numbers in the following show
lines.
N.B. the numbers to be replace could be stored in a file and the same solution used with the following amended solution.
parallel -q sed -Ei '/{}/{h;:a;n;/^show/!ba;G;s/\((.*)\n.* (.*)/(\2,\1/}' file :::: fileContainingNumbers
Upvotes: 0