Michael Gruenstaeudl
Michael Gruenstaeudl

Reputation: 1783

Vertical alignment of lists with different content in bash

Assume two lists with different content. For simplicity, let us assume that these lists contain only alphanumeric strings. I would like to combine and vertically align the two lists in bash.

user$ cat file1
foo
foo
bar
qux

user$ cat file2
foo
bar
bar
baz
qux

user$ sought_command file1 file2
foo foo
foo -
bar bar
- bar
- baz
qux qux

The delimiter between the values per line (here a single whitespace) does not need to be selected by the user, but can be hard-coded. So can the placeholder for a gap (here a dash).

EDIT:

Ideally, this command is not restricted to two input lists, but can take any number of input files, each comparing to the first one specified.

user$ sought_command file1 file2 file2
foo foo foo
foo - -
bar bar bar
- bar bar
- baz baz
qux qux qux

Upvotes: 2

Views: 516

Answers (3)

webb
webb

Reputation: 4340

Here is a very likely faster version of Ohad Eytan's answer, only relevant for extremely large or many files:

diff -t -y file1 file2 | tr -s ' ' | tr '[<>]' '-' | grep -o '\S\+ \S\+'

Upvotes: 1

tale852150
tale852150

Reputation: 1628

Just diff and sed will work when comparing just 2 files

diff -y file1 file2 | sed 's/[[:space:]]\+/ /g' | sed 's/[<,>]/- /g'

Results (line up nicely):

foo foo
foo -
bar bar
 -  bar
 -  baz
qux qux

Will need more work in order to handle input files greater than 2.

Upvotes: 0

Ohad Eytan
Ohad Eytan

Reputation: 8464

You can use diff with -y flag to get:

$ diff -y file1 file2
foo                             foo
foo                               <
bar                             bar
                                  > bar
                                  > baz
qux                             qux

and together with tr and sed:

$ diff -t -y file1 file2 | tr -s ' ' | sed 's/[<>]/-/' 
foo foo
foo -
bar bar
 - bar
 - baz
qux qux

Upvotes: 3

Related Questions