0

I need an awk command to merge these two files that have matching values.

Color:Green
Color:Yellow 
Color:Orange

And

Green:Yes
Orange:Yes

And get

 Color:Green:Yes
 Color:Orange:Yes
  • 9
    Please show what you have tried so far. It's better to be specific about what you are stuck on. (If you're asking us to just write it without you trying...that's not really what we're here for.) – B Layer Dec 13 '17 at 14:47
  • Why do you need AWK? There might be a more suitable tool. – simlev Dec 13 '17 at 17:00
1

Using join and sort in bash:

$ join -t: -1 2  <( sort -t: -k2 colours.txt ) <( sort selected.txt )
Green:Color:Yes
Orange:Color:Yes

For correct ordering of fields:

$ join -t: -1 2 -o1.1,1.2,2.2 <( sort -t: -k2 colours.txt ) <( sort selected.txt )
Color:Green:Yes
Color:Orange:Yes

join performs a relational JOIN operation on sorted input data. In this case, the join field is the colour, which appears as the second :-delimited field in the first file and as the first :-delimited field in the second file.

With join -t: -1 2 we make join pick the the second field from the first file as the "join key" field (the first field is the default) and with the two <(...) (process substitutions in bash) we provide the sorted data. The first sort is the only one that's "special" as it sorts the first file on its second :-delimited field, the colour.

The second example above uses the -o flag to explicitly specify what we'd like to see in the output and in what order.

| improve this answer | |
0

Here is an awk solution:

awk -F':' 'NR==FNR{seen[$1]=$2; next} 
    ($2 in seen){print $0":"seen[$2]; next}1' file2  file1

Inputs:

==> file1 <==
Color:Green
Color:Yellow
Color:Pinky
Color:Orange

==> file2 <==
Green:Yes
Orange:Yes
Yellow:No

Output:

Color:Green:Yes
Color:Yellow:No
Color:Pinky
Color:Orange:Yes
| improve this answer | |
0

Assuming file1 is

color:green
color:yellow
color:orange

and file2 is

green:yes
orange:yes

I guess this will generate what you want:

awk -F ':' 'FNR==NR{a[$1]=$2;next}($2 in a){print a[$1]":"a[$2]} file2 file1

OUTPUT:

color:green:yes
color:orange:yes
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.