0

I have two files:

first file:

ab34,ax,55,gt
ab46,56,thy,ix
ab34,tg,47,xy
at87,kl,89,th
ab46,ut,87,er

second file:

x1,ab34,78,got
wq,at87,100,op
90,ab46,la,gf

expected result:

ab34,ax,55,gt,x1,ab34,78,got
ab46,56,thy,ix,90,ab46,la,gf
ab34,tg,47,xy,x1,ab34,78,got
at87,kl,89,th,wq,at87,100,op
ab46,ut,87,er,90,ab46,la,gf

I want to grep lines in the second file based on the values in first column of the first file. The ideal output would be printing the first file with the lines that match from the second file. I write simple unix commands but this one is a bit trickier for me, apparently needs a loop function.

1
  • 1
    Do you really want to "grep" the second file - or match first file column 1 against second file column 2? – steeldriver Jul 5 '19 at 17:35
1

Looks like idea case for UNIX commands, you need to sort first:

cat 1|sort > 1.sort
cat 2|sort -t, -k2  > 2.sort
join -t, -2 2 1.sort 2.sort

Did I just do you homework?

0

I'm making a lot of assumptions about what you actually want, but this produces your desired sample output. So perhaps my interpretation of the question is correct:

awk 'NR==FNR{a[$2]=$0; next} {print $0,a[$1]}' FS=, OFS=, file2 file1

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.