Arthur Hills
Arthur Hills

Reputation: 37

insert a specific line after occurrence with Unix

I need insert a new line with specific content after find a pattern in text1 file with shell.

I have a file text_file_1.txt with this content:

aaaaaa
bbbbbb
patternrefrefref
cccccc
aaaaaa
patternasdasd
pattern
zzzzzz

and a text_file_2.txt with this content:

111111
333333
555555

and I need insert the first line of text_file_2.txt (that is, 111111) when I find the first occurrence of "pattern" of text_file_1.txt and 333333 when I find the second occurrence of "pattern (always pattern)...

Final result will be:

aaaaaa
bbbbbb
pattern_refrefref
111111
cccccc
aaaaaa
pattern_asdasd
3333333
pattern
555555
zzzzzz

I found how to insert a new line with a new text after a pattern but always insert the same text, I don't need that.

Upvotes: 2

Views: 114

Answers (2)

Sir. Hedgehog
Sir. Hedgehog

Reputation: 1290

i think you are looking for something like this...

sed '/what_you_want_to_find /a what_you_want_to_add' text_file_1.txt

if you also want to save the changes in the same file just use this:

sed -i '/what_you_want_to_find /a what_you_want_to_add' text_file_1.txt

to help you a bit more, at the point that you add what new you want to get printed, so in what_you_want_to_add, you can do it like this. Save each line every time in variable outside of the sed, for example you want to get line number 5.

line= awk 'NR==5' text_file_2.txt

and you can use the variable each time to print the new line, so it would like this in your case. sed '/what_you_want_to_find /a $line' text_file_1.txt

Upvotes: 2

anubhava
anubhava

Reputation: 784908

This is easily done using awk:

awk 'FNR==NR{a[FNR]=$0; next} 1; /pattern/{print a[++i]}' text_file_2.txt text_file_1.txt

aaaaaa
bbbbbb
patternrefrefref
111111
cccccc
aaaaaa
patternasdasd
333333
pattern
555555
zzzzzz
  • In the first block FNR==NR we are reading all the lines from file2 and storing them in an indexed array a.
  • While iterating through file2 whenever we encounter pattern we print one line from array and increment the counter.

Upvotes: 3

Related Questions