Help with a For loop and variables

Greetings. I'm completely new to shell scripting and quickly trying to catch on. Here's my scenario:

I have a text file, named ip.txt, containing IP addresses. I want to automatically perform a whois query on each address in the file, search the output for the country, and then put both the IP address and the corresponding country together into a new file.

Here's what I've come up with so far:

The problem with this, obviously, is that it doesn't list the IP address in the output file.

To the best that I can tell, I somehow need to store the grep results as a variable, and then maybe echo both variables into a new file.

Am I on the right track?

In the event that it matters, the system I'm trying to do this on is Debian 6.0.3.

Thanks!

That's a dangerous use of backticks and useless use of cat. A 'while read' loop will be safer and faster.

You also don't need to reopen the same file 9000 times when processing 9000 IP addresses -- you can redirect the input and output of entire code blocks once instead of things inside them over and over.

Yes, store the result in a variable then print them both.

while read IP
do
        COUNTRY=$(whois "$IP" | grep -i "country:")
        echo "$IP: $COUNTRY"
done < ip.txt > out.txt
1 Like

Wow, I obviously have a lot to learn. :slight_smile:

Thank you very much.

edit: removed duplicate

Some of these things are less than obvious, for sure. I don't know where everyone picks up `cat file` though.

In my case, Google. :smiley: