Specialized grep script

I have been (unsuccessfully) trying to write a script that will do the following:

  • for each line of an input file (that contains IP address),
  • the script searches the target file for any lines containing said IP address
  • if it finds a line (or lines) it writes the line(s) to output
  • if the line is not found the script just writes the IP address (being searched for) to output

Any assistance would be appreciated.

I am not sure the format of your files but the script will be like this. If the input_file is large, using AWK instead of while-loop may make sense.

cat input_file | while read IP; do
  grep -F $IP target_file || echo $IP
done

Thanks much, that worked exactly as needed.

How about

grep -ofinput_file target_file

?

Hi RudiC,
I don't think so. I think ddirc wants entire lines from target_file for lines in target_file that contain one of the strings in input_file (presumably as a complete word; not just as a substring of a word) AND for any lines in input_file that were not found in target_file , ddirc wants those line from input_file to be printed as well.

There is no need to start an extra process nor to create a pipeline for this. It can be done more efficiently with just:

while read IP; do
  grep -F $IP target_file || echo $IP
done < input_file

But, as mentioned above, it isn't clear to me that this is sufficient. If a line in input_file is:

29.15.17.2

that grep will match the following lines in target_file :

IP address 129.15.17.2 is on serverA
IP address 29.15.17.29 is on serverX

Hi ddirc,
You said the code MasWag suggested is working for you. Do you want lines like those in the above example to be matched? If not, please give us sample input and a clear description of any field delimiters that can be used to find the boundaries between the start and end of an IP address in target_file and please also show us the corresponding sample output you hope to produce.

Also, knowing what operating system and shell you're using always helps us give you suggestions that will stand a better chance of working in your environment.

1 Like