1

Grep doesn't seem to work inside the loop.

prashant@prashant-Inspiron-3542:~/Downloads/files_for_script$ grep "$ GR" firstFIle | cut -b3-
GR:NSM1_base_to_diffuser
GR:NSM2_base_to_diffuser
GR:FSin_not_imposed_to_FS_out
GR:Diffuser_to_FSin_not_imposed
GR:FSin_imposed_to_FS_out
GR:FSin_imposed_to_not_imposed
GR:FS_out_to_MLI
GR:FSout_to_OSR


prashant@prashant-Inspiron-3542:~/Downloads/files_for_script$ grep GR:NSM1_base_to_diffuser secondFile 

Groupi:    20.00   6.0355E+01    5.0409E+02    NSM1_base - GR:NSM1_base_to_diffuser - Primary Region
 Groupj:    20.00   0.0000E+00    2.4418E+03    DIFFUSER - GR:NSM1_base_to_diffuser - Secondary Region

but it's not showing any output when I am using it inside the for loop.

prashant@prashant-Inspiron-3542:~/Downloads/files_for_script$ for line in `grep "$ GR" firstFIle | cut -b3-`; do grep $line secondFile; done
prashant@prashant-Inspiron-3542:~/Downloads/files_for_script$ 
prashant@prashant-Inspiron-3542:~/Downloads/files_for_script$ 

I don't seem to understand what am I doing wrong here.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
prashant
  • 231
  • 1
  • 3
  • 8
  • This doesn't answer your question directly, but a for loop is superfluous here, just pipe the grep/cut from the one file to a grep for the second file since grep can take search criteria from stdin: `grep "$ GR" firstFIle | cut -b3- | grep -f - secondfile` – JNevill Aug 03 '17 at 17:06
  • If you want to find all lines in both of two files, see [BashFAQ #36](http://mywiki.wooledge.org/BashFAQ/036) -- which will be *far* more efficient anyhow. – Charles Duffy Aug 03 '17 at 17:13
  • I am trying to use the every line of output of `grep "$ GR" firstFIle | cut -b3- ` as strings to search in the secondFile. I don't think this will help here. Could you check once more. – prashant Aug 03 '17 at 17:13
  • @prashant, that's exactly what JNevill's answer does. It **does** help you. – Charles Duffy Aug 03 '17 at 17:14
  • @prashant, `grep -f -` is telling grep to read the list of strings to search for from stdin. – Charles Duffy Aug 03 '17 at 17:14
  • 1
    Related, btw: [Don't Read Lines With `for`](http://mywiki.wooledge.org/DontReadLinesWithFor) – Charles Duffy Aug 03 '17 at 17:16
  • BTW, to be able to test our answers, we'd need *literal* content from `firstFile` (not that same content after it's been through `cut`) in the question. This is part of making a code sample "verifiable" such that a question provides a [mcve]. – Charles Duffy Aug 03 '17 at 17:18
  • ok got it.. its working now...thanks very much – prashant Aug 03 '17 at 17:38

0 Answers0