问题
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
回答1:
Try this awk one liner:
awk 'NR==FNR{a[NR]=$0;next}1;/cat/{print a[++i]}' file2 file1
test:
$ cat file1
I am a cat
I am a dog
I am a dog
I am a cat
I am a dog
$ cat file2
line 1
line 2
$ awk 'NR==FNR{a[NR]=$0;next}1;/cat/{print a[++i]}' file2 file1
I am a cat
line 1
I am a dog
I am a dog
I am a cat
line 2
I am a dog
回答2:
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.
$ awk '1; /cat/{getline this<"file2";print this}' file1
I am a cat
line1
I am a dog
I am a dog
I am a cat
line2
I am a dog
The 1
at the start of the program prints the current line from file1
, whatever that is. The second condition in the script checks for your magic word, then reads from file2
and prints it. Your memory footprint remains tiny, because you aren't populating an array with the contents of one of the files.
来源:https://stackoverflow.com/questions/38621535/merge-lines-of-two-text-files-when-pattern-is-found