System Administration & Network Administration
bash shell shell-scripting
Updated Wed, 31 Aug 2022 04:42:54 GMT

How to add a variable into a grep command


I'm running the following grep command

var=`grep -n "keyword" /var/www/test/testfile.txt`

This work just as expected but I need to insert the file name dynamically from a loop like so:

var=`grep -n "keyword" /var/www/test/`basename ${hd[$i]}`.txt`

But obviously the use of ` brakes this with a unexpected EOF while looking for matching ``' and unexpected end of file

Any ideas of away around this?




Solution

Please don't use `, and use a function:

mygrep() { grep -n "yourkeyword" "/var/www/test/${1##*/}.txt"; }
for (( i= 0; i < ${#hd[@]}; i++ )); do yourvar=$(mygrep "${hd[$i]}"); done




Comments (5)

  • +0 – FGS? A little harsh. Sorry I was only asking im new to BASH/Shell give me a chance to learn that's why I ask — Nov 27, 2012 at 10:39  
  • +0 – Fair enough: the use of backticks (`) to execute commands is discouraged and has been deprecated for many years now; $() is cleaner and offers less surprises, plus it is easier to quote and nest. — Nov 27, 2012 at 11:13  
  • +0 – thank you, I have only learnt from reading other peoples code, I guess doing this may not be the best way as the code could be old, like in this case, lesson learnt. — Nov 27, 2012 at 11:17  
  • +1 – I wholeheartedly recommend Greg Wooledge's wiki: wiki.wooledge.org for all things bash. — Nov 27, 2012 at 11:23  
  • +0 – question on the above code what goes the @ do (or symbolise) in the ${#hd[@]}; line? — Nov 27, 2012 at 12:02