1

I've researched many similar Q&As but am still stuck on a solution.

I have 2 files.

File1

cow
aaaaa
brown
bbbbb
often
ccccc
farts
ddddd

File2

In File2, with 'space' as a delimiter, then col 1="brown" and col2="149,456,foo". Also, File1 and File2 are not in the same order (sort doesn't work here, I want to count on the matching key to make the replacement).

brown 149,456,foo
cow 192,231,bar
farts 81,2007,tip
often 427,541,top

I want to create File3

cow 192,231,bar
aaaaa
brown 149,456,foo
bbbbb
often 427,541,top
ccccc
farts 81,2007,tip
ddddd

In other words, note column1-in-File2 (brown) and search for it in File1. When that match is found in File1, replace the match with the entire line of corresponding File2 (brown 149,456,foo).

I've tried this:

$ awk 'NR==FNR{a[NR]=$0;next}{$6=a[FNR]}1' file2 file1

But the results seem to take every row1 and then prints it next to with row1 from the other file, there's no match/replace involved.

brown     brown 149,456,foo
aaaa     cow 192,231,bar
cow     farts 81,2007,tip
bbbbb     often 427,541,top
farts     
ccccc     
often     
ddddd 

I'd like to use awk or sed. Much thanks in advance for any suggestions!

1 Answer 1

3

Try:

$ awk 'FNR==NR{a[$1]=OFS $2;next} {print $0 a[$1]}' file2 file1
cow 192,231,bar
aaaaa
brown 149,456,foo
bbbbb
often 427,541,top
ccccc
farts 81,2007,tip
ddddd

How it works

  1. FNR==NR{a[$1]=OFS $2;next}

    While reading file2 (the first file on the command line), we add an entry to associative array a under the key of the first field, $1. The entry consists of the output field separator, OFS, followed by the second field, $2. We then skip the rest of the commands, and jump to start over on the next line.

  2. print $0 a[$1]

    While reading file1 (the second file on the command line), we print each line followed by whatever the value of array a is for the line.

2
  • Why not just store $2 only and then print $0, a[$1]? Wouldn't that be simpler and clearer?
    – Wildcard
    Dec 22, 2017 at 2:44
  • 1
    @Wildcard Yes but print $0, a[$1] puts a space after $0 even if a[$1] is empty. If it was my project, I probably wouldn't care about an extra trailing space and I'd use code just as you suggested. Other people, including many on SE sites, sometimes obsess on such spaces. Consequently, on SE, I usually try to avoid them.
    – John1024
    Dec 22, 2017 at 5:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .