Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only difference from diff

Tags:

linux

diff

sed

I have this code , how to improve it

diff  -b -i -w  out.txt out2.txt  
 | grep '^>' 
 | sed 's/^>//g' 
 | sed ':a;N;$!ba;s/\n/ /g' 

example data (out.txt)

abc def ghk
abc def2 ghk
abc def ghk

123 333 555
566 3423 23
566 3423 3542

example data (out2.txt)

abc def2 ghk
abc def ghk
abc def ghk

123 555 555
fsdjhfsda sd
566 3423 3542

expected result :

abc def ghk  123 555 555  fsdjhfsda sd
like image 336
Yehuda Avatar asked Aug 04 '26 04:08

Yehuda


2 Answers

Here's one simple way:

echo `diff -biw out.txt out2.txt | sed -n 's/^> //p'`

If you want to use use grep alone -- and if you can take advantage of GNU grep's formatting features -- you could use this:

diff --unchanged-group-format= --changed-group-format=%\> \
  --new-line-format='%l ' -biw out.txt out2.txt

which is probably the fastest method, and it doesn't require a large memory buffer when your files are big. (Both your original sed solution and the echo solution would keep lines in memory until the end, but this will spit them out as it goes.) The command itself is pretty verbose, though. Note also that it leaves one extra space at the end of the output.

like image 101
Rob Davis Avatar answered Aug 06 '26 17:08

Rob Davis


Looks like comm + tr is similar:

comm --nocheck-order -13 out.txt out2.txt | tr '\n' ' '

Also you can put all sed and grep into one sed:

diff  -b -i -w out.txt out2.txt | sed '/^>/!{d};:a;N;$!ba;s/\n>/ /g;s/^>//'


 $ diff  -b -i -w  out.txt out2.txt | grep '^>' | sed 's/^>//g' | sed ':a;N;$!ba;s/\n/ /g'
123 555 555  fsdjhfsda sd  566 3423 3542
 $ diff  -b -i -w out.txt out2.txt | sed '/^>/!{d};:a;N;$!ba;s/\n>/  /g;s/^>//'
123 555 555   fsdjhfsda sd   566 3423 3542
 $ comm --nocheck-order -13 out.txt out2.txt | tr '\n' '  '
123 555 555 fsdjhfsda sd 566 3423 3542 
like image 32
rush Avatar answered Aug 06 '26 16:08

rush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!