Tuesday, October 15, 2013

How to Use Grep in For Loop

www.unixbabuforum.inI am trying to use the grep command within for loop but not getting any output on execution. 

for i in `cat patch_order`;do grep $i;done 
118666-34 
118667-34 
125136-31 
125137-31 

Ctrl+d 

www.unixbabuforum.inTry this:
root# cat /var/tmp/patch_to_rm |while read patch 
> do 
> grep $patch /var/tmp/kk/10_Recommended_CPU_2012-01/patch_order 
> if [ $? -eq 0 ] ; then 
> echo $patch >> found_list.txt 
> elif [ $? -eq 1 ] ; then 
> echo $patch >> not_found_list.txt 
> else 
> echo "Error processing $patch. Aborted script." 
> exit -2 
> fi 
> done 
118666-34 
118667-34 
120543-25 
122911-28 
125136-31 
125137-31 
141552-04 
root# 
root# /usr/xpg4/bin/grep -f /var/tmp/patch_to_rm /var/tmp/kk/10_Recommended_CPU_2012-01/patch_order 
118666-34 
118667-34 
120543-25 
122911-28 
125136-31 
125137-31 
141552-04 
root# for i in `cat /var/tmp/kk/10_Recommended_CPU_2012-01/patch_order`; do grep $i /var/tmp/patch_to_rm;done 
118666-34 
118667-34 
120543-25 
122911-28 
125136-31 
125137-31 
141552-04 



www.unixbabuforum.inYou do not have the search string in grep., the line should be like: 
for i in `cat patch_order`; 
do 
grep string $i 
done

And if patch_order is file the more elegant and sample way is: 
grep string patch_order

 "string" is the sequence of symbols you search in the file. And grep will display only the lines, which contain this sequence. You can also use wildcard to mach for example only line which start with particular symbol: 
grep ^11 patch_order 
This will display only lines, starting with symbols sequence 11 


www.unixbabuforum.inIf you have a file which is a list of interesting things, in your case, a list of patches, with one token or word per line, then you may use grep -F (or fgrep) to find those items in other files. 
you may not need to put grep in a for-loop. 
here's an example:

[grep -Ff log.one  … list of files ...]

says search (grep) using the tokens in a file (-F) named (f) "log.one" through the … list of files … 
So, if you are looking for list of patches in a list of files, you could simply: 

grep -Ff patch_order *.log   # or whatever your files are named

Here's example:


ittoolbox.$ grep -Ff log.one *
bar.txt:foo
log.one:foo
log.one:bar
log.two:foo
mkdirDemo:barely recovered from the 14-character limit on filenames, there were
ittoolbox.$ cat log.one
foo
bar
ittoolbox.$

0 comments:

Post a Comment

 
Design by BABU | Dedicated to grandfather | welcome to BABU-UNIX-FORUM