grep and awk help

I have 2 files

file1:

192.168.1.1 ABC
192.168.1.2 AAA

file 2:

BBB 192.168.1.1
CCC 192.168.1.2
DDD 192.168.1.3

Output:

192.168.1.1 ABC BBB
192.168.1.2 AAA CCC

The basic thing I want to do is that I want to match ip addresses and if they match, print the matching lines from file1 and append the first field of the matching lines from file2.
I am trying to use grep -f and awk to achieve this, but I can't get the output right.

192.168.1.1 appears two times in file2. How d you want to handle this case?

To keep the forums high quality for all users, please take the time to format your posts correctly.

First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags

```text
 and 
```

by hand.)

Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.

Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.

Thank You.

The UNIX and Linux Forums

Watch what you wish for, it just might come true :wink:

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

Sorry that was a typo on my part. I edited my post to address that.

---------- Post updated at 12:31 PM ---------- Previous update was at 12:14 PM ----------

Hi, thank you so much for your help, but I just tried this and it is not outputting correctly. :frowning:

Use GNU awk (gawk), New awk (nawk) or POSIX awk (/usr/xpg4/bin/awk)

Yes, sorry your example works for my example. However, with different IP addresses it doesn't seem to be working. For example:

File 1:
192.168.1.1 ABC
192.168.1.2 AAA
10.10.1.23 weeee

File 2:
BBB 192.168.1.1
CCC 192.168.1.2
DDD 192.168.1.3
yaaa 10.10.1.23


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

The following output produces:

192.168.1.1 ABC BBB
192.168.1.2 AAA CCC
10.10.1.23 weeee

Answer @ripat question first and will see what we can do.

Check this thread