[英]How to compare 2 files line by line with terminal
我有 2 個文本文件需要逐行比較。
我基本上想根據它是否匹配為每一行輸出“匹配”或“不匹配”。
我試過閱讀一些教程並使用diff
和dircmp
類的東西,但似乎無法找到一種方法來做到這一點。 我不在乎它是 bash、perl、python 等。這兩個文件都是 243 行。
Linux 中是否有可用的命令來執行此操作?
這是我正在尋找的一個例子......
文件 1
Test
Hello
Example
檔案 2
Test
What
Example
我想輸出這個:
matching
not matching
matching
在 perl 中:
#!/usr/bin/perl
use strict;
use File::Slurp;
my @file1 = read_file 'file1', { chomp => 1 };
my @file2 = read_file 'file2', { chomp => 1 };
foreach (@file1) {
my $line = shift @file2;
print $_ eq $line ? "not matching\n" : "matching\n";
}
您所追求的是以下形式的 awk 腳本:
$ awk '(NR==FNR){a[FNR]=$0;next}
!(FNR in a) { print "file2 has more lines than file1"; exit 1 }
{ print (($0 == a[FNR]) ? "matching" : "not matching") }
END { if (NR-FNR > FNR) print "file1 has more lines than file2"; exit 1}' file1 file2
此腳本基於您的兩個文件均為 243 行。 您需要在運行腳本之前對這兩個文件進行排序,即sort file1.txt > file1.sorted.txt
並且對另一個文件進行相同的sort file1.txt > file1.sorted.txt
。
#!/bin/bash
while read file1 <&3 && read file2 <&4
if [[ $file1 == $file2 ]]; then
echo "matching" >> three.txt
else
echo "not matching" >> three.txt
fi
done 3</path/to/file1.sorted.txt 4</path/to/file2.sorted.txt
上面的腳本將逐行讀取每個文件,使用 if 語句比較輸入。 如果兩個字符串相同,它會將“匹配”寫入three.txt
否則它將“不匹配”寫入同一個文件。 循環將遍歷每一行。
您必須對兩個文件中的數據進行排序以進行比較。 我已經用以下數據對其進行了測試:
一個.sorted.txt
abc
cba
efg
gfe
xyz
zxy
二.sorted.txt
abc
cbd
efh
gfe
xyz
zmo
三.txt
matching
not matching
not matching
matching
matching
not matching
最好使用專用的 linux 文件比較工具,例如 Meld 或 Vimdiff,它們非常直接且非常方便。
您可以輸入“which meld”來檢查是否安裝了它,如果沒有找到,請使用以下命令進行安裝:
sudo apt-get install meld
此外,這里有一個簡單的python腳本來獲得您要求的結果:
#!/usr/bin/env python3
with open ('1.txt') as f1:
lines1 = f1.readlines()
lines1 = [line.rstrip() for line in lines1]
with open ('2.txt') as f2:
lines2 = f2.readlines()
lines2 = [line.rstrip() for line in lines2]
for i, line in enumerate(range(min(len(lines1),len(lines2)))):
print("matching") if lines1[i] == lines2[i] else print("not matching")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.