0

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?

twigg
  • 154
  • 1
  • 4

2 Answers2

3

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
adaptr
  • 16,576
  • 23
  • 34
  • 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 – twigg Nov 27 '12 at 10:39
  • 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. – adaptr Nov 27 '12 at 11:13
  • 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. – twigg Nov 27 '12 at 11:17
  • 1
    I wholeheartedly recommend Greg Wooledge's wiki: http://wiki.wooledge.org for all things bash. – adaptr Nov 27 '12 at 11:23
  • question on the above code what goes the @ do (or symbolise) in the ${#hd[@]}; line? – twigg Nov 27 '12 at 12:02
  • It evaluates to all members of the array, and is needed to calculate the number of elements with ${#} – adaptr Nov 27 '12 at 12:57
  • Thank you learnt a lot from this one small piece of code :) I do seem to be getting a problem with this though. When I'm running it, its putting a /dev in the folder path like so: /var/www/test/dev/hd1.txt I guess its taking it from the following line /var/www/test/${1#*/}.txt but I can't see where its taking the /dev from – twigg Nov 27 '12 at 13:19
  • My bad, I should have given you the greedy match; post updated. – adaptr Nov 27 '12 at 13:30
3

You can also use:

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

(observe the quotings, and, as adaptr mentioned, don't use backticks, but $(...) instead, as it's nestable).