user2587385
user2587385

Reputation: 5

How to join two files in shell script

I have two file in unix. I just want to add two file content with column wise

file 1:                  file 2:

2013-09-09 5656          2013-09-09 4321
2013-09-10 1234          2013-09-10 3234
                         2013-09-11 5056
                         2013-09-12 1256

I used the following:

paste -d " " file1 file2>file3 

But it's not working as expected

I need the output like:

2013-09-09 5656     2013-09-09 4321
2013-09-10 1234     2013-09-10 3234
                    2013-09-11 5056
                    2013-09-12 1256

paste -d " " file1 file2 returns:

2013-09-09 5656     2013-09-09 4321
2013-09-10 1234     2013-09-10 3234
2013-09-11 5056
2013-09-12 1256

Upvotes: 0

Views: 2757

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85775

pr is the tool for the job:

$ pr -m -t file1 file2

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361575

paste doesn't try to align the files neatly in columns. It merely inserts a delimiter between columns. If the default paste file1 file2 doesn't work for you, then you'll need to take matters into your own hands.

For example:

# Assign file1 and file2 to file descriptors 3 and 4 so we can read from them
# simultaneously in the loop.
exec 3< file1 || exit
exec 4< file2 || exit

while true; do
    # Keep looping as long as we've read a line from either file.
    # Don't stop until both files are exhausted.
    line_read=0
    read a <&3 && line_read=1
    read b <&4 && line_read=1
    ((line_read)) || break

    # Use `%-20s' to ensure each column is 20 characters wide at minimum.
    printf '%-20s %-20s\n' "$a" "$b"
done

Upvotes: 0

Related Questions