2015-02-24 43 views
1

我知道如何在文件中搜索字符串,並用字符串刪除行在它使用sed。如何讀取文件A中的每行/字符串A,並在文件B中找到包含字符串的行,並在ubuntu中對其進行刪除

sed -i '/pattern/d' ./file 

但是我需要找到的字符串很多,有沒有辦法讓它自動化呢?例如,從文件A逐行讀取字符串,並將其作爲變量傳遞給sed,以便sed可以找到包含該字符串的行並將其刪除?

謝謝。

+1

請給例子fileA'的',' fileB'和你喜歡的輸出。 – Jotne 2015-02-24 07:06:33

回答

0

要麼你可以結合使用命令替換與sed-f

$ cat file 
one two foo 
bar three four 
qux 
quux 
blah 
blupp 

$ cat exclude 
foo 
bar 
^qu 

$ sed -i -f <(sed 's#\(.*\)#/\1/d#g' exclude) file 

$ cat file 
blah 
blupp 

但除非你知道你的模式將不包含字符,sed解釋這不是很強勁。

更好:只需使用grep有一個臨時文件:

$ grep -vf exclude file > file.new && mv file.new file 

$ cat file 
blah 
blupp 
0

可以完成這件事使用grep得到。 詳見man grep(尋找-v-f選項)

樣品:

$ cat File1 
Line with pattern1 
Line with jskjdksdjk 
Line with ioweuwue 
Line with pattern2 
Line with sydsudsd 

$ cat File2 
pattern1 
pattern2 

$ grep -vf File2 File1 
Line with jskjdksdjk 
Line with ioweuwue 
Line with sydsudsd 

要替換同一文件(File1),grep -vf File2 File1 > tmp && mv tmp File1

相關問題