awk script: check if all words(fields) from one file are contained in another file

纵然是瞬间 提交于 2019-12-11 11:50:07

问题


I am new to awk scripting. I want to do a field by word (field) comparison of two files File1.txt and File2.txt. The files contain a list of | (pipe) separated field.

    File 1:
    -------------------
    aaa|bbb|ccc|eee|fff
    lll|mmm|nnn|ooo|ppp
    rrr|sss|ttt|uuu|vvv

    File 2: 
    -------------------
    aaa|bbb|ccc|eee|fff
    rrr|sss|ttt|uuu|vvv
    rrr|sss|ttt|uuu|uuu

We compare the same line no. in both the files.

Fields in Line 1 of both file match.

In Line 2 all the fields (lll, mmm, nnn, ooo, ppp) donot not match with all fields (rrr, sss, ttt, uuu, vvv) in line 2 of File 2. Similarly the 5th field (vvv, uuu) of 3rd line in both the files donot match.

Hence Line no. 2 and Line no. 3 should get echoed by bash.

Both files will follow an order.


回答1:


this line should do:

awk 'NR==FNR{a[FNR]=$0;next}a[FNR]!=$0' file1 file2

output:

rrr|sss|ttt|uuu|vvv
rrr|sss|ttt|uuu|uuu



回答2:


Two compare two files, better use already inbuilt command sdiff:

 sdiff File1 File2

This will display the lines which differ in both files.

Doing with awk.

awk -F '|' 'NR==FNR{a[$0];next}!($0 in a){print $0}' file1 file2



回答3:


The following lines may be adapted following needs, another language like perl may be more appropriate

i=1
while read -r -u4 l1 || read -r -u5 l2; do
  if [[ $l1 != $l2 ]]; then
    echo "$i: $l1 != $l2"
  fi
  ((i+=1))
done 4<file1 5<file2


来源:https://stackoverflow.com/questions/18945691/awk-script-check-if-all-wordsfields-from-one-file-are-contained-in-another-fi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!