I am looking for an awk or sed solution to combine 2 files based on a matched pattern, like so: The PATTERN in this case is "cat". The number of lines in file 2 will always equal the number of pattern matches in file 1.
File 1:
I am a cat
I am a dog
I am a dog
I am a cat
I am a dog
File 2:
line 1
line 2
Merged File:
I am a cat
line 1
I am a dog
I am a dog
I am a cat
line 2
I am a dog
The
NR==FNR
construct is very handy, but it may be risky if the file you intend to load into memory is very very large.Instead, awk can read from two files at once.
The
1
at the start of the program prints the current line fromfile1
, whatever that is. The second condition in the script checks for your magic word, then reads fromfile2
and prints it. Your memory footprint remains tiny, because you aren't populating an array with the contents of one of the files.Try this awk one liner:
test: