0

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.

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

2 Comments

Thanks for the help. It works but it appends starting from a new line for example line one(1) will have the original value and line two(2) will have the appended value.
This works sed "s/.$/|$(cat file2)/" file1 > file3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.