visakh
visakh

Reputation: 2553

Merging two files horizontally and formatting

I have two files as follows:

File_1

Austin
Los Angeles
York
San Ramon

File_2

Texas
California
New York
California

I want to merge them horizontally as follows:

Austin       Texas
Los Angeles  California
York         New York
San Ramon    California

I am able to merge horizontally by using paste command, but the formatting is going haywire.

Austin Texas
Los Angeles California
York New York
San Ramon California

I realize that paste is working as it is supposed to, but can someone point me in the right direction to get the formatting right.

Thanks.

Upvotes: 4

Views: 6797

Answers (3)

Thor
Thor

Reputation: 47099

If you have an idea about the field width, you could do something like this:

IFS_BAK="$IFS"
IFS=$'\t'
paste file_1 file_2 \
| while read city state; do 
    printf "%-15s %-15s\n" "$city" "$state"
  done
IFS="$IFS_BAK"

Or this shorter version:

paste file_1 file_2 | while IFS=$'\t' read city state; do
  printf "%-15s %-15s\n" "$city" "$state"
done

Or use the column tool from bsdmainutils:

paste file_1 file_2 | column -s $'\t' -t

Upvotes: 1

Chris
Chris

Reputation: 935

paste is using a tab when 'merging' the file, so maybe you have to post-process the file and remove the tab with spaces:

paste File_1 File_2 | awk 'BEGIN { FS = "\t" } ; {printf("%-20s%s\n",$1,$2) }'

result:

Austin              Texas
Los Angeles         California
York                New York
San Ramon           California

Upvotes: 6

Marcin Zaluski
Marcin Zaluski

Reputation: 727

Firstly you have to check number of characters in the longest line. Than you may use fmt to pad line from the first file to greater length. Finish it using paste.

Upvotes: 1

Related Questions