Bash スクリプト: 2 つのテキスト ファイルを比較する

Bash スクリプト: 2 つのテキスト ファイルを比較する

これを効率的に行うにはどうしたらよいかと思っています。a.txt と b.txt という 2 つのファイルがある場合、次の操作を実行する bash スクリプトを作成したいと考えています。

a.txt 内の '*' を含む行のうち、b.txt に存在しない行はすべて、タイムスタンプ付きで b.txt の末尾に追加されます。

最初と最後の部分はできるのです grep "*" a.txt echo "$(date)" >> b.txt が、残りの部分はどうすればよいかわかりません。

答え1

b.txt ファイルを台無しにしないように、結果には 3 番目のファイルを使用することをお勧めします。以下を試してみてください。

cp b.txt c.txt 
for line in $(grep '*' a.txt); do
    # for each line found in a.txt
    echo "Found: $line"
    grep -q $line b.txt   # check its presence in b.txt
    if [ $? -ne 0 ]; then
        # if the result of the grep is not equal to 0
        # it means that the line has not been found in b.txt
        # then print the line in a third file with the leading timestamp
        echo "$(date): $line" >> c.txt
    fi
done

'*' を検索している行がどのように構成されているかわからないので、grep を改善するだけでよいことは明らかです。

関連情報