user2008558
user2008558

Reputation: 341

Merge columns from multiple files in Unix

I need help merging the content of two pipe delimited files.

I have

file1

a|b|1|test|0
v|3|r|rest|4
5|4|a|two|3
3|5|r|help|4

file2

01May2014

I want

file3

a|b|1|test|0|01May2014
v|3|r|rest|4|01May2014
5|4|a|two|3|01May2014
3|5|r|help|4|01May2014

Any help, especially ones involving the "awk"statement, will be appreciated.

Upvotes: 0

Views: 365

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

Since it appears that you know that there is just one line in file2, you could use:

awk -v extra=$(<file2) -e '{ OFS="|"; print $0, extra }' file1

Or in sed:

sed -e 's/$/|'"$(<file2)"/' file1

Both of these avoid processing two files in the main program (awk or sed); they let the shell do the work on file2 and use the results of that work.

The $(<file2) notation is equivalent to, but more efficient than, $(cat file2) and is a Bash extension.

Upvotes: 1

Steve
Steve

Reputation: 54392

Using the AWK language, here's one way:

awk 'FNR==NR { r = $0; next } { print $0, r }' OFS="|" file2 file1

Results:

a|b|1|test|0|01May2014
v|3|r|rest|4|01May2014
5|4|a|two|3|01May2014
3|5|r|help|4|01May2014

Upvotes: 1

Jared Casper
Jared Casper

Reputation: 168

Depending on how robust or generic it needs to be, something like this could work:

sed "s/$/|$(cat file2)/" file1 > file3

This of course assumes file2 is just a single line to be concatenated on to the end of each line in file1. The sed command s/foo/bar/ replaces all occurrences of "foo" with "bar". In this case, it replaces the end of a line ("$") with | followed by the output of the command "cat file2". It does this for file1, redirecting the output into file3.

Upvotes: 0

Related Questions