2

I have two files

file1.txt

a|1|cd a|2|cd a|4|cd 

file2.txt

a|0001|hj|df a|0002|ed|nb a|0003|vf|za a|0004|er|ns a|0005|oi|lk 

I need a create new file with the lines matched by de second column of the files, I try by then next code

awk -F"|" 'NR==FNR{a[$2]++;next} a[$2] ' file1.txt file2.txt 

but no found records, because file1.txt in second column doesn't contain 0 at the left I have the instruction

awk -F"|" 'NR==FNR{a[$(printf("%09d\n", $2))]++;next} a[$2]' 

but doesn't work.

The result must be:

file3.txt

a|0001|hj|df a|0002|ed|nb a|0004|er|ns 

1 Answer 1

2

Adding zero to field forces awk to treat it as a number, not a string:

$ awk -F"|" 'NR==FNR{a[$2+0]++;next} a[$2+0] ' file1.txt file2.txt a|0001|hj|df a|0002|ed|nb a|0004|er|ns 

As a string 0001 is different from 1. By adding zero to each, we convert them to numbers which results in the comparison that you want.

2
  • [$2+0]++ is for convert string to number ??? @John1024 Commented Oct 28, 2015 at 23:48
  • @MiguelAngel $2+0 forces awk to treat $2 as a number, not a string. The ++ part of this command is separate and unrelated. Commented Oct 28, 2015 at 23:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.