user3834663
user3834663

Reputation: 543

match the string in a file and print the next column

I have two files input1.txt and input2.txt.

input1.txt has following details:

abcd.net
bcad.net
cagh.net
degh.net
usna.net

input2.txt has following details:

abcd.net 169.254.0.2
bcad.net 169.254.0.3
cagh.net 169.254.0.4
us-1212-qwe.net 169.254.232.50
us-cisco.net 10.120.2.3
degh.net 169.254.0.5
usna.net 169.254.0.6
ab1234.net 169.254.0.7
catorr.net 169.254.0.8

I need to get the corresponding IP details of the servers listed in "input1.txt" from the file "input2.txt"

Output should be like this:

abcd.net 169.254.0.2
bcad.net 169.254.0.3
cagh.net 169.254.0.4
degh.net 169.254.0.5
usna.net 169.254.0.6

My code as shown below is not working properly. Please help.

  for i in `cat input1.txt`; do more input2.txt | grep -w "^$i"; done

Upvotes: 0

Views: 159

Answers (2)

William Pursell
William Pursell

Reputation: 212198

awk 'FNR==NR{ip[$1]=$2} FNR!= NR {print $1, ip[$1]}' input2.txt input1.txt

This reads through input2.txt and builds an array of the desired data, indexed by the first column. Then it reads intput1.txt and for each line prints the host plus the data in the array.

Note, the answer given above no longer applies, as the question has been edited. For the edited question, you can do:

 awk 'FNR==NR{ip[$1".net"]=$2} FNR!= NR {print $1, ip[$1]}' input2.txt input1.txt

but this is not the best general solution. (eg, hardcoding the text ".net" is a terrible approach, but for a quick hack this is fine.)

Upvotes: 2

karakfa
karakfa

Reputation: 67467

alternatives to awk

join <(sort input1) <(sort input2)

abcd.net 169.254.0.2
bcad.net 169.254.0.3
cagh.net 169.254.0.4
degh.net 169.254.0.5
usna.net 169.254.0.6

or good old grep

grep -f input1 input2

abcd.net 169.254.0.2
bcad.net 169.254.0.3
cagh.net 169.254.0.4
degh.net 169.254.0.5
usna.net 169.254.0.6

Upvotes: 1

Related Questions