[英]compare two files with numbers and find the difference , using linux shell command
[英]Matching numbers from two files using Linux
我想使用Linux命令或腳本比較兩個文件中的數據。 第一個文件由一系列的7個數字組成,后接一行的名稱,文件中包含多行數字和名稱。 數字不能在同一行上重復,但可以在另一行上找到,並且將按順序在每行上列出。
File1示例:
01 02 03 04 05 06 07 Name1
11 12 13 14 15 16 17 Name2
01 03 05 11 12 14 16 Name3
...
我想知道File1中的數字行中的哪一行與File2中的另一組數字匹配。 File2中的數字不會重復,將按順序排序。
File2示例:
01 02 03 04 05 11 12 13 14 15 16 18 20
只要File1中的一行數字與File2中的任何數字匹配,我都希望顯示匹配的行,包括名稱。
輸出示例:
01 03 05 11 12 14 16 Name3
如果沒有匹配項,我想顯示“ No Match”或類似內容。
我是Linux和腳本文件的新手,感謝您提供的所有幫助。 謝謝。
使用Awk相當容易。 讓我們來看看這個零碎的東西。
NR==FNR { for (i=1; i<=NF; ++i) a[$i]=1; next }
當我們讀取第一個輸入文件時, NR==FNR
條件為true。 我們遍歷輸入字段,並為每個數組分配關聯數組a
鍵。 現在,它包含第一個文件的輸入字段(運行時將確保它是File2
)。
在另一個文件的行上,將字段循環到倒數第二個字段(我們跳過最后一個包含標識符的字段,例如Name2
)。 如果有任何值不在a
,放棄此行。
{ for (i=1; i<NF; i++) if (! ($i in a)) next }
否則,請打印。
1
(孤單1
是Awk慣用語,如果我們進入腳本的這一部分,它將打印輸入。這是一個不成立的情況,沒有任何操作;默認操作是打印輸入行。)
我們將所有內容收集到一個shell腳本代碼片段中,
awk 'NR==FNR { for (i=1; i<=NF; ++i) a[$i] = 1; next }
{ for (i=1; i<NF; i++) if (! ($i in a)) next } 1' File2 File1
假定File2
僅包含一行。 如果要擴展到多行,Awk的功能會有些緊張。 在那時,也許考慮切換到Perl或Python(或您碰巧熟悉的其他任何東西)。 Awk的吸引力在於它很簡單-您可以在一天內學習它,並在一周內編寫好的腳本。
這個(相當丑陋的)bash腳本將在給定的樣本數據上產生正確的結果:
# Read numbers against which to match from File2 into array.
read -a match_array <<< "$(cat File2)"
# Traverse each line in File1
while read -a line
do
if [ "$line" != "" ]
then
# Counter for the number of matches
match=0
# Strip off the name on the end, leaving only numbers to match
for n in "${line[@]:0:7}"
do
for m in "${match_array[@]}"
do
if [ "$n" == "$m" ]
then
# Successfully matched a number, increment counter.
match=$(($match + 1))
fi
done
# Correct number of matches
if [ "$match" == "7" ]
then
echo ${line[@]}
fi
done
fi
done < File1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.