Bash
如何使 diff 命令忽略第二個文件(bash)的某些行?
例如:
文件 1.txt:
I need to buy apples. I need to run the laundry. I need to wash the dog. I need to get the car detailed.
文件2.txt
I need to buy apples. I need to run the laundry. I need to wash the car. I need to get the car detailed.
文件 3.txt
I need to wash the car.
如果我這樣做
diff file1.txt file2.txt
了,如果 file3.txt 中存在的語句存在於 file2.txt 中,則 diff 命令應該忽略它。因此,在這種情況下,應該沒有區別。使用忽略標誌 (
diff -I "$line"
) 將無濟於事,因為它在兩個文件中都找到了模式。我怎樣才能做到這一點?
一種解決方法是去除相應的行,然後對其進行比較。也就是說,兩者
file1
都file2
看起來像:I need to buy apples. I need to run the laundry. I need to get the car detailed.
您可以使用
grep
,perl
和的組合來執行此操作sed
:$ lines_to_ignore=$(grep -nFf file3 file2 | perl -pe 's|^(\d+):.*|$1s/.//g;|') $ echo $lines_to_ignore 3s/.//g; $ diff <(sed "$lines_to_ignore" file1) <(sed "$lines_to_ignore" file2) $ echo $? 0
- 我
grep
用來獲取匹配的行(連同行號)file2
- 然後我使用
perl
從輸出中獲取行號grep
並從中發出 sed 命令(Ns/.//g
刪除第 N 行上的每個字元)。- 然後我使用程序替換將
sed
在文件上執行這些命令的結果提供給diff
.