diffコマンドを利用して、2つのファイルの差分比較を行い、その結果を ファイルに出力するシェルスクリプトのサンプルです。 Webコンテンツの移行作業において、移行前と移行後のファイルの差分が 発生していないか検証する際に便利です。
■サンプルスクリプト(sabun.sh)
[root@tanyao ~]# cat sabun.sh
#!/bin/sh
# 必ず比較対象ファイルと同階層にこのシェルを配置して実行してください!!
# 比較対象(パス指定禁止)
FILE1=file1.txt
FILE2=file2.txt
# ファイル名にスペースを含むファイルはNG扱いとする
if [ `grep " " ${FILE1} | wc -l` != 0 ] ; then
grep " " ${FILE1} > diff_NG_${FILE1}
fi
if [ `grep " " ${FILE2} | wc -l` != 0 ] ; then
grep " " ${FILE2} > diff_NG_${FILE2}
fi
# 並び替え
grep -v " " ${FILE1} | sort > sort_${FILE1}
grep -v " " ${FILE2} | sort > sort_${FILE2}
# 比較
diff -y -t -d sort_${FILE1} sort_${FILE2} > diff.txt
# 同一レコードの抽出
grep -v "<" diff.txt | grep -v ">" | grep -v "|" > diff_same.txt
# 第1ファイルにのみ存在
grep -e "<" -e "|" diff.txt | cut -d " " -f 1 > diff_only_${FILE1}
# 第2ファイルにのみ存在
grep ">" diff.txt | cut -d ">" -f 2 > diff_tmp_${FILE2}
grep "|" diff.txt | cut -d "|" -f 2 >> diff_tmp_${FILE2}
sed -e 's/^ //' diff_tmp_${FILE2} > diff_only_${FILE2}
# 作業ファイルの削除
rm -rf sort_${FILE1}
rm -rf sort_${FILE2}
rm -rf diff_tmp_${FILE2}
exit 0
[root@tanyao ~]#
■テストデータ準備
[root@tanyao ~]# cat file1.txt /var/log/httpd/ /var/log/httpd/error_log /var/log/httpd/error_log-20110103 /var/log/httpd/access_log /var/log/httpd/access_log-20110103 [root@tanyao ~]# [root@tanyao ~]# cat file2.txt /var/log/httpd/ /var/log/httpd/error_log /var/log/httpd/error_log-20110104 /var/log/httpd/access_log /var/log/httpd/access_log.1 /var/log/httpd/access_log-20110103 [root@tanyao ~]#
■使用例および結果確認
[root@tanyao ~]# ./sabun.sh [root@tanyao ~]# cat diff_only_file1.txt /var/log/httpd/error_log-20110103 [root@tanyao ~]# cat diff_only_file2.txt /var/log/httpd/access_log.1 /var/log/httpd/error_log-20110104 [root@tanyao ~]# cat diff_same.txt /var/log/httpd/ /var/log/httpd/ /var/log/httpd/access_log /var/log/httpd/access_log /var/log/httpd/access_log-20110103 /var/log/httpd/access_log-20110103 /var/log/httpd/error_log /var/log/httpd/error_log [root@tanyao ~]#
■diffオプション
-y, --side-by-side
side-by-side 出力形式を用いる。
side-by-side 形式
ファイルは 2 列に表示され、間に溝 (gutter) が置かれる。溝には以下のマーカーのいずれか 1 つが含まれる。
' ' 対応する行が共通である。つまり、両方の行が同一であるか、違いが --ignore オプションのいずれかによって無視された。
| 対応する行が異なる。両方とも完全か、両方とも不完全かである。
< ファイルは異なり、1 番目のファイルにだけこの行が含まれている。
> ファイルは異なり、2 番目のファイルにだけこの行が含まれている。
( 1 番目のファイルにだけこの行が含まれているが、違いは無視される。
) 2 番目のファイルにだけこの行が含まれているが、違いは無視される。
サイト継続にご協力ありがとうございます。こちらの情報が何かのお役にたてれば幸いです。m(_ _)m