[英]Using inverse grep to compare two .txt files
我有兩個.txt文件“ test1.txt”和“ test2.txt”,我想使用反grep(UNIX)來查找test2.txt中的所有行,這些行不包含test1.txt中的任何行
test1.txt僅包含用戶名,而test2.txt包含較長的文本字符串。 我只希望test2.txt中的行不包含在test1.txt中找到的用戶名
會是這樣嗎?
grep -v test1.txt test2.txt > answer.txt
您幾乎就在那里,只是錯過了命令中的一個選項(即-f)。您的解決方案應使用-f標志,請參見下面的示例會話,以演示相同的內容
示范會議
$ # first file
$ cat a.txt
xxxx yyyy
kkkkkk
zzzzzzzz
$ # second file
$ cat b.txt
line doesnot contain any name
This person is xxxx yyyy good
Another line which doesnot contain any name
Is kkkkkk a good name ?
This name itself is sleeping ...zzzzzzzz
I can't find any other name
Lets try the command now
$ # -i is used to ignore the case while searching
$ # output contains only lines from second file not containing text for first file lines
$ grep -v -i -f a.txt b.txt
line doesnot contain any name
Another line which doesnot contain any name
I can't find any other name
Lets try the command now
您使用的是哪種口味的Unix? 這將使我們對從命令行可以使用的功能有更好的了解。 當前您所擁有的將無法使用,您正在尋找比較兩個文件的diff
命令。
您可以對OS X 10.6執行以下操作,我已經在家中對其進行了測試。
diff -i -y FILE1 FILE2
diff
比較文件-i
無關緊要,因此Hi和HI仍然相同。 最后, -y
將並排輸出結果。如果要將信息輸出到文件中,可以執行diff -i -y FILE1 FILE2 >> /tmp/Results.txt
他們可能是實現此目標的更好方法。 沒有grep,但是這是一個可行的解決方案
grep -v -P "($(sed ':a;N;$!ba;s/\n/)|(/g' test1.txt))" test2.txt > answer.txt
解釋一下:
$(sed ':a;N;$!ba;s/\\n/)|(/g' test1.txt)
是一個嵌入式sed命令,它輸出一個字符串,其中test1.txt中的每個換行符都用)|(
然后將輸出插入到perl樣式正則表達式( -P
)中供grep使用,以便grep在test2.txt中搜索text1.txt中的每一行,並僅返回test2.txt中不包含行的內容。由於-v
參數,因此為test1.txt。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.