LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Need a shell script help - grepping list of entries from another file? (https://www.linuxquestions.org/questions/linux-general-1/need-a-shell-script-help-grepping-list-of-entries-from-another-file-891222/)

Jykke 07-12-2011 12:42 AM

Need a shell script help - grepping list of entries from another file?
 
I made this short shell script for having a file1 giving list of entries that I want to grep out of file2.

Code:

#!/bin/sh
for line in `cat $1`
do
 grep -A30 $line $2
 echo **--------------------------------------------------------
done

Unfortunately the grepping is not so exact as I might have characters like ; or space and so on in my search list. How can I improve it?

colucix 07-12-2011 01:12 AM

Please show us an example of the input file ($2 in your script) and the search list ($1) especially the not working part of them. Also take in mind that you can use the -f option of grep to read patterns from a file, so that you don't need to use a loop:
Code:

grep -A30 -f $1 $2

Jykke 07-12-2011 03:59 AM

Your example works straight out of the box and does not mess the stuff up like my trial. Thx.

However, I am still at least academically interested in the solution. So for this reason.
If file 1 has for example:
CONNECTOR BEHAVIOR, NAME=M1901479;SPW_WF-1901479

It begins by listing all lines from file2 where only word CONNECTOR is present and then with BEHAVIOR,
and then I believe it searches NAME=M1901479;SPW_WF-1901479

So all in all I think it is allergic to spaces in my file1 and treats a line as three separate strings
So perhaps it is in the layout of for - loop and using cat.

colucix 07-12-2011 07:40 AM

Quote:

Originally Posted by Jykke (Post 4412429)
So all in all I think it is allergic to spaces in my file1 and treats a line as three separate strings. So perhaps it is in the layout of for - loop and using cat.

Yes. That's exactly the reason: the loop is iterated over the three fields separated by space. The shell uses the blank space (together with TAB and newline) to separate fields (check the IFS built-in variable). You can alter the value of IFS to protect the space from being considered the field separator or - better - you can do:
Code:

while read line
do
  something with "$line"
done < $1

In this case the read statement takes care of assigning the whole line to the loop variable (despite the presence of blank spaces or any other special symbol). Just put the reference to $line inside double quotes when you use it.


All times are GMT -5. The time now is 09:24 AM.