问题
I recently asked a similar question How To Insert File Contents After Line Match While Escaping Backslash only to realize I need to do the opposite.
Using the code from that question, I have tried:
sed '/<\\tag>/i file2' file1
2nd attempt:
awk '/<\\tag>/{print;system("cat File2.txt");before} 1' File1.txt
However, I'm unable to get it to insert one line before the match.
Example:
File1.txt
Hello <[World!]> 1
Hello <[World!]> 2
File2.txt:
<thanks>
<tag>
<example>
<new>
<\new>
<\example>
<\tag>
<\thanks>
Desired output:
<thanks>
<tag>
<example>
<new>
<\new>
<\example>
Hello <[World!]> 1
Hello <[World!]> 2
<\tag>
<\thanks>
If you could please help me insert the file contents after a line match while escaping a backslash, I would really appreciate it.
回答1:
$ awk 'FNR==NR{n=n $0 ORS; next} /<\\tag>/{$0=n $0} 1' file1 file2
<thanks>
<tag>
<example>
<new>
<\new>
<\example>
Hello <[World!]> 1
Hello <[World!]> 2
<\tag>
<\thanks>
回答2:
In your awk solution you need to do following changes :
1. Interchange the file names as you've to work upon File2.txt and print the File1.txt contents where the match is found.
2. Remove the print; in awk as you don't want to print the <\tag> twice in your output.
3. There is no keyword before in awk. Remove it please.
awk '/<\\tag>/{system("cat File1.txt");} 1' File2.txt
Other possible solution is :
$ awk 'FNR==NR{f1[++i]=$0; l=i; next} /<\\tag>/{ for(i=1; i<=l; i++) print f1[i]}1' File1.txt File2.txt
<thanks>
<tag>
<example>
<new>
<\new>
<\example>
Hello <[World!]> 1
Hello <[World!]> 2
<\tag>
<\thanks>
FNR==NR{f1[$0]=$0; next} Stores the content of File1.txt in array f1/<\\tag>/{ for(i in f1) print f1[i]} : While iterating over File2.txt if the match is found then print the array contents.
来源:https://stackoverflow.com/questions/46719414/insert-file-contents-one-line-before-match-while-escaping-backslash