LoginSignup
1
0

More than 1 year has passed since last update.

【Linux】ファイルの変更部分のみ取得する方法

Posted at

はじめに

以下のような2つのファイルがある場合に内容を比較して変更箇所のみ取得する方法について記載します。

old.txt
変更なし
変更なし
変更なし

new.txt
変更なし
変更なし
変更あり
追加
追加
追加

diffコマンド

diffコマンドを使用して次のように実行することで変更箇所のみ取得できます。

$ diff --old-line-format='' --unchanged-line-format='' --new-line-format='%L' old.txt new.txt
変更あり
追加
追加
追加
  • --old-line-format
    1番目のファイルだけにある行の出力に使用するフォーマットを設定する。

  • --unchanged-line-format
    両方のファイルに共通な行の出力に使用するフォーマットを設定する。

  • --new-line-format
    2番目のファイルだけにある行の出力に使用するフォーマットを設定する。

  • %L
    行頭などに何もつけず1行ずつ出力する。
    +%Lとすると以下のようになります。

    $ diff --old-line-format='' --unchanged-line-format='' --new-line-format='+%L' old.txt new.txt
    +変更あり
    +追加
    +追加
    +追加
    

    また%lとすると以下のようになります。

    $ diff --old-line-format='' --unchanged-line-format='' --new-line-format='%l' old.txt new.txt
    変更あり追加追加追加
    

commコマンド

commコマンドを使用して次のように実行しても変更箇所のみ取得できます。

$ comm -13 old.txt new.txt
変更あり
追加
追加
追加
  • -13
    old.txtのみに含まれる行と両方のファイルに含まれる行を出力しないようにする。
    すなわち変更や追加があった行のみ出力する。

ただしファイルがsortされていない正しく比較できず以下のようなエラーが出力されます。

comm: file 2 is not in sorted order
comm: input is not in sorted order

これを出力させないようにするにはsortしてからcommするかsortする必要のない場合には以下のようにオプションを付けます。

comm --nocheck-order old.txt new.txt
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0