4

I have two files in these formats:

file1 :

air
smell
hand
dude
road
cat

file 2:

air,4,21,01,13,3,2
smell,21,4,2,5,6
dude,1,31,42,1
road,1,4,2,1,4
cat,1,5,6,3,1
hand,1,4,2,1,6
mouse,1,3,5,6,2

what I want to do is print the entire row of file 2, if the first string in column 1 of file 2 is found in file 1, and I want to keep the order of file 1.

expected output:

air,4,21,01,13,3,2
smell,21,4,2,5,6
hand,1,4,2,1,6
dude,1,31,42,1
road,1,4,2,1,4
cat,1,5,6,3,1
3

This should do it:

awk -F, 'FNR==NR {a[$1]; next}; $1 in a' file1 file2

edit:

Interpreted the wrong file for the ordering. A new attempt (requires gawk if that is acceptable)

gawk -F, '
    FNR==NR {a[NR]=$1; next}; 
    {b[$1]=$0}
    END{for (i in a) if (a[i] in b) print b[a[i]]}
' file1 file2

edit 2:

With nowmal awk, and swapping the files around:

awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' file2 file1
3
join -t, -1 2 -2 1 <(nl -s, -ba -nrz file1 | sort -t, -k2) \
<(sort -t, -k1 file2) | sort -t, -k2 | cut -d, -f1,3-

The lines in file1 are numbered and the result is sorted on 2nd field. This is then joined with file2 (sorted on 1st field):

air,000001,4,21,01,13,3,2
cat,000006,1,5,6,3,1
dude,000004,1,31,42,1
hand,000003,1,4,2,1,6
road,000005,1,4,2,1,4
smell,000002,21,4,2,5,6

the result is then sorted on 2nd field (i.e. the line numbers) to restore the original line order and then the same 2nd field is removed with cut:

air,4,21,01,13,3,2
smell,21,4,2,5,6
hand,1,4,2,1,6
dude,1,31,42,1
road,1,4,2,1,4
cat,1,5,6,3,1
  • i get a return message Missing name for redirect for some reason. I'm pretty sure I'm using your code as is. Maybe it's my system specifics? – Nolohice Jul 16 '15 at 17:18
  • Ubuntu 14.04 & tc shell – Nolohice Jul 16 '15 at 17:23
0

You can use the simple grep command.

grep -f file1 file2
  • This is close, but does not meet the requirement of preserving the output in the order of file1. – Jeff Schaller Oct 29 '15 at 19:37
  • My bad, I over looked the "I want to keep the order of file 1" part in the question. – Venkat Madhav Oct 29 '15 at 19:49

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.