简体   繁体   中英

How can I compare rows in Unix text files and add them together in another text file?

I have a text file 1 that has 3 columns. The first column contains a number, the second a word (which can be either a sting like dog or a number like 1050), the third column a TAG in capital letters. I have another text file 2 that has 2 columns. The first column has a number, the second one has a TAG in capital letters. I want to compare every row in my text file 1 with every row in my text file 2. If the TAG in column [3] in text file 1 is the same as the TAG in column [2] in text file 2, then I want to store the number in text file 1 next to the number in text file 2 next to the word in text file 1. There are no duplicate TAGS in text file 2 and there are no duplicate words in text file 1. Illustration:

Text file 1

2    2737    HPL
32   hello   PLS
3    world   PLS
323  .       OPS

Text file 2

342  HPL
56   PLS
342  DCC
4    OPS

I want:

2   342  2737
32  56   hello
3   56   world
323 4  .

You can do this in awk like this:

awk 'FNR==NR { h[$2] = $1; next } $3 in h { print $1, h[$3], $2 }' file2 file1

The first part saves the key and column from file 2 in an associative array ( h ), the second part compares column 3 from file 1 to this array and prints the relevant parts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM