Insert File Contents One Line Before Match While Escaping Backslash

我与影子孤独终老i 提交于 2020-01-05 04:00:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!