0

I need to diff two unsorted text files with the output marking every line as either old, new, or unchanged. The marks should appear at the beginning or end of the line, and there should be no other output apart from these marked lines.

For example, say we have the following two files:

old.txt

unchanged line one
unchanged line two
unchanged line three
deleted line one
deleted line two
deleted line three
unchanged line four
unchanged line five
unchanged line six

new.txt

unchanged line one
unchanged line two
unchanged line three
unchanged line four
unchanged line five
inserted line one
inserted line two
inserted line three
unchanged line six

GNU diff allows you to specify printing formats for old, new, and unchanged "input groups", but these get applied only to the first line in a run of old/new/unchanged lines. For example, running diff --old-group-format='- %<' --new-group-format='+ %>' --unchanged-group-format='| %=' old.txt new.txt results in

| unchanged line one
unchanged line two
unchanged line three
- deleted line one
deleted line two
deleted line three
| unchanged line four
unchanged line five
+ inserted line one
inserted line two
inserted line three
| unchanged line six

However, I need the diff to look something like this, where every line gets marked:

| unchanged line one
| unchanged line two
| unchanged line three
- deleted line one
- deleted line two
- deleted line three
| unchanged line four
| unchanged line five
+ inserted line one
+ inserted line two
+ inserted line three
| unchanged line six

Can I do this with GNU diff, either alone or in combination with other common command-line text processing tools like sed? A portable (POSIX) solution might be even better, provided it is not too hairy.

3

GNU diff supports line formats as well as group formats:

$ diff --old-line-format='- %L' --new-line-format='+ %L' --unchanged-line-format='| %L' old.txt new.txt
| unchanged line one
| unchanged line two
| unchanged line three
- deleted line one
- deleted line two
- deleted line three
| unchanged line four
| unchanged line five
+ inserted line one
+ inserted line two
+ inserted line three
| unchanged line six

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.