简体   繁体   中英

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM