sedを使用してdiff出力に特定の行を切り取り、追加する

sedを使用してdiff出力に特定の行を切り取り、追加する

2つのディレクトリ間のdiffコマンドの出力をdifferenceOutput.txt

現在は2行しかないので、differenceOutput.txtすべての行はAまたはB形式を持ちます。ここで、AとBは次のとおりです。

ㅏ)

Only in /tmp/__tmp_comp206_alex/test_files/: file_1.txt

2)

Files /tmp/__tmp_comp206_alex/test_files/file_3.conf and /tmp/__tmp_comp206_alex/diff_dir/file_3.conf differ

を使用して、A形式のすべての行をC形式に変更し、B形式のすべての行をD形式に変更したいとsed思いますdifferenceOutput.txt。ここで、CとDは次のようになります。

氏)

/tmp/__tmp_comp206_alex/test_files/file_1.txt is missing

ディ)

/tmp/__tmp_comp206_alex/diff_dir/file_3.conf differs 

どうすればいいですかsed? sed 構文は非常に混乱しています。私はこれを理解しようと数時間を費やしましたが、それを理解することはできません。誰でも私を助けることができますか?

ベストアンサー1

ここです。 2つの簡単なsed代替

a='Only in /tmp/__tmp_comp206_alex/test_files/: file_1.txt'
b='Files /tmp/__tmp_comp206_alex/test_files/file_3.conf and /tmp/__tmp_comp206_alex/diff_dir/file_3.conf differ'

printf "%s\n%s\n" "$a" "$b" |
sed -e 's!^Only in \([^:]*\)/: \(.*\)!\1/\2 is missing!' -e 's!^Files .* and \(.*\) differ$!\1 differs!'

出力

/tmp/__tmp_comp206_alex/test_files/file_1.txt is missing
/tmp/__tmp_comp206_alex/diff_dir/file_3.conf differs

説明する

  • レシピでは区切り文字として!notを使用しました。それ以外の場合は、すべての一致をエスケープし、文字列内のすべての項目を置き換える必要があります。/seds/match/replacement//
  • \1一致部分の一致項目\2( ) などでエスケープされた角かっこ式を置き換えます。\(...\)

最大の仮定は、ファイル名に出力にコロンやその他の一致する単語が含まれていないことですdiff。出力はせいぜい壊れやすいので、自分のループを転がして目的の出力を直接生成することをお勧めdiffします。 (これは強力なソリューションを好むものです。)findcmp -s

#!/bin/bash
src='/tmp/__tmp_comp206_alex/test_files'
dst='/tmp/__tmp_comp206_alex/diff_dir'

( cd "$src" && find -type f -print0 ) |
    while IFS= read -r -d '' item
    do
        if [[ ! -f "$dst/$item" ]]
        then
            printf "%s is missing\n" "$dst/$item"

        elif ! cmp -s "$src/$item" "$dst/$item"
        then
            printf "%s differs\n" "$dst/$item"
        fi
    done

おすすめ記事