2

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.

4
  • Please work on formatting your question properly. Commented Apr 19, 2016 at 10:56
  • What have you tried, and how did it fail? I would turn to Awk (hint: NR==FNR), though I guess it could be possible to do in sed as well. Commented Apr 19, 2016 at 10:59
  • I have tried something like this: sed '/pattern/a 111111' file Commented Apr 19, 2016 at 11:01
  • sorry @derlarsschneider my english es poor ;) Commented Apr 19, 2016 at 11:03

2 Answers 2

3

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.
Sign up to request clarification or add additional context in comments.

1 Comment

It's awesome! it's work fine :D thank you very much. You have got that I waste a lot of hours working on files manually ^_^
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.