Serdar Dalgic
Serdar Dalgic

Reputation: 1342

Show only changed lines with diff, not newly added lines

I'm curious if there is a way to get only changed lines with diff, not the newly added lines?

I mean, let's say I have two files file1 and file2.

file1 is:

abc=123
def=234
klm=10.10
xyz=6666

file2 is:

abc+=123
def=234
klm=10.101
xyz=666
stackoverflow=1000
superuser=2000
wtf=911

what I want is giving a command like diff <parameters> file1 file2 and getting an output like

- abc=123
+ abc+=123
- klm=10.10
+ klm=10.101
- xyz=6666
+ xyz=666

Such output is welcomed too:

- abc=123
+ abc+=123
  def=234
- klm=10.10
+ klm=10.101
- xyz=6666
+ xyz=666

I don't want the

stackoverflow=1000
superuser=2000
wtf=911

lines in the output.

Is there a way to get this functionality with the parameters of diff in Linux?

Upvotes: 2

Views: 1848

Answers (2)

lethalman
lethalman

Reputation: 2019

Try diff -U0, it should give you only the changed lines without further context.

Upvotes: 1

perreal
perreal

Reputation: 98118

A simple Perl script:

use strict;
use warnings;

my ($fname1, $fname2) = ($ARGV[0], $ARGV[1]);

my %conf;
open (my $input1, "<", "$fname1") or die("open $fname1: $!");
while (<$input1>) { 
  chomp; 
  my @v = split(/\+?=/);
  $conf{$v[0]}=$_; 
}
close $input1;

open (my $input2, "<", "$fname2") or die("open $fname2: $!");
while (<$input2>) {
  chomp;
  my @v = split(/\+?=/);
  if (defined ($conf{$v[0]}) && $_ ne $conf{$v[0]}) {
    print "- $conf{$v[0]}\n";
    print "+ $_\n";
  }
}
close $input2;

Output

- abc=123
+ abc+=123
- klm=10.10
+ klm=10.101
- xyz=6666
+ xyz=666

Upvotes: 1

Related Questions