シェルスクリプトを使用して2つの異なるファイルの1対1行を比較する

シェルスクリプトを使用して2つの異なるファイルの1対1行を比較する

2つのファイルがあります。

File1         File2

abc           abc
cde           cde,xyz,efg,hij,...,n

efg           lmn,opq,weq,...n

今比較したいです。ファイル1行1そしてファイル2行12号線そして2号線など。ただし、File2では、単一行に「カンマ」で区切られた複数の項目を含めることができます。

今入ってみるとファイル1対応する行項目と一致します。ファイル2結果は良いでしょう。それ以外の場合は違いが表示されます。

たとえば、

File1         File2

cde           cde,xyz,efg,hij,opt

cde両方のファイルに結果があるため、結果は良好でなければなりません。

アイテムの違いを含むdiffなどのシェルスクリプトを書くのに役立ちますか?

ベストアンサー1

きれいではないかもしれませんが、次のようなものが始まるかもしれません。

# 1. Read lines from file1 as string, and file2 as comma-separated array.
while read -r a && IFS=, read -ra b <&3; do
    # 2. If both empty lines, continue.
    if [[ "$a" == "" && ${#b[@]} == 0 ]]; then
        continue
    fi
    # 3. Start assuming diff.
    diff=1
    # 4. Loop fields in $b.
    for e in ${b[@]}; do
        # Compare field in $b with $a, if match then abort.
        if [[ "$e" == "$a" ]]; then
            diff=0
            break
        fi
    done
    # 5. If no match found, print line from $b.
    if [[ $diff == 1 ]]; then
        # Join array with <space>comma.
        line=$(printf ", %s" "${b[@]}")
        # Print line, excluding leading <space>comma.
        printf "%s\n" "${line:2}"
    fi
# Input argument one as file 1 to stdin, and argument two as file 2 to
# file descriptor 3.
done < "$1" 3<"$2"

通常、次のように使用されます。

$ ./myscript file1 file2

今、Python、Perl、awkなどを使用する方が良いでしょう。

おすすめ記事