0
votes

I am looking for shell script that will replace in the file couple of thousand lines after lines consisting of constant pattern and variable patern. The patterns mapping is in external file.

Source/target file abc.txt has got such shape:

something not to be changed
123: aaa
bla bla

something else
123: abc
bla bla

And something more
123: ccc
bla bla

pattern mapping file pat.txt has got such shape:

abc pattern     xyz
aaa pattern     xxx
ccc pattern     zzz

Now I need to change the line

bla bla

to proper pattern i.e. line after 123: abc should be changed to xyz

I have clue on specific steps like: Changing the line after matching pattern

sed '/abc/!b;n;c/xyz' abc.txt

or displaing lines before pattern:

grep -B1 "bla bla" abc.txt

or displaying lines after mathing pattern:

grep -A1 "123" abc.txt

or returning rest of the pattern mapping from pat.txt

grep "abc" pat.txt | sed -n -e 's/^.*pattern  //p'

but I have no clue how to make it together. Any help would be appreciated. Thanks.

1

1 Answers

0
votes

First, to change an entire line to a fixed string, I prefer s to c, like this:

/abc/{n;s/.*/xyz/;}

just because c is so fussy about newlines (at least in my version of sed). Use c if you prefer it.

So here is the sed script we need:

/^123: abc$/{n;s/.*/xyz/;}
/^123: aaa$/{n;s/.*/xxx/;}
/^123: ccc$/{n;s/.*/zzz/;}

My approach would be to convert your pat.txt into that script, by means of another sed command:

sed 's|^\([^ ]*\) pattern *\(.*\)$|/^123: \1$/{n;s/.*/\2/;}|' pat.txt