2017-10-12 74 views
0

我試圖使用的代碼,我發現這裏:Insert contents of a file after specific pattern match如何插入文件的內容線路賽後當逃脫反斜槓

然而,當我添加一個反斜槓代碼,這是行不通的。那麼,我按照這裏的說明:Slash and backslash in sed更改sed中的分隔符。但是,當我這樣做時,插入(應該是幾行)會變成數千。

這裏是我的嘗試:

sed ':<\tag>: r file1.txt' file2.txt 

例子:

FILE1.TXT

Hello World 1 
Hello World 2 

FILE2.TXT:

<thanks> 
<tag> 
<example> 
<new> 
<\new> 
<\example> 
<\tag> 
<\thanks> 

所需的輸出:

<thanks> 
<tag> 
<example> 
<new> 
<\new> 
<\example> 
<\tag> 
Hello World 1 
Hello World 2 
<\thanks> 

如果你可以請幫我在一行匹配後插入文件內容,同時轉義一個反斜槓,我真的很感激它。

回答

2

試試這個

sed '/<\\tag>/r file2' file1 

我想你交換文件1和文件2。

+0

我做了交換file1和2.現在修復。但是,我沒有得到那個輸出:-( – DomainsFeatured

+0

你還需要用另一個反斜槓來轉義反斜線。 – karakfa

+0

是的,我已經試過'<\\tag>'和'<\\\tag>'前兩個都不適合我 – DomainsFeatured

1

請嘗試使用以下awk一次。

awk '/<\\tag>/{print;system("cat File2.txt");next} 1' File.txt 

要將輸出保存到File.txt本身,以下內容可能會對您有所幫助。

awk '/<\\tag>/{print;system("cat File2.txt");next} 1' File.txt > temp_file && mv temp_file File.text 
+0

This works。Thanks Ravinder – DomainsFeatured

+0

嘿Ravinder,我怎麼修改它,以便它插入一行之前? – DomainsFeatured

+0

@DomainsFeatured,請檢查我的第二個回答並讓我知道它是怎麼回事 – RavinderSingh13

1

相同的答案您的其他問題(見https://stackoverflow.com/a/46720002/1745001),只打印新紀錄之後,而不是在目標前行:

awk 'FNR==NR{n=n ORS $0; next} /<\\tag>/{$0=$0 n} 1' file1 file2 

我強烈推薦這本書有效AWK編程,第4版,由阿諾德羅賓斯。

+1

聽起來很棒,請試試這個,再次感謝Ed :-) ....並且,它的工作原理! – DomainsFeatured