Search code examples
shellforeachgrepcshbackticks

foreach: grep backtick in for-loop


How would one grep backtick from files in a for-loop.

I would like to run grep for a pattern '`define'. The pattern works in standalone grep command but fails in for-loop.

foreach xxx ( `grep -r '`define' $idirectory --no-filename | sed -e 's ; //.* ; ; ' -e 's ; #.* ; ; ' -e 's ; ^\s* ; ; ' | grep -v ^$ | sort -n | awk '{print $2}' | uniq -d`)
  echo $xxx
end

The backticks are conflicting in the for-loop.

regards

Srisurya


Solution

  • Simply, don't use ' and escape the backtick with backshlash.

    So, the next didn't works:

    grep -r '`def' *
    

    and prints

    No matching command
    

    But this:

    grep -r \`def *
    

    works and prints

    ewdwedwe `define`
    

    So, simiarly for your script, the next works (file btick.tcsh):

    #!/bin/tcsh
    set greparg = \`def
    foreach xxx ( `grep -l $greparg *` )
        echo ===$xxx===
    end
    

    and pruduces the next result

    ===btick.tcsh===
    ===btick1.txt===
    ===btick2.txt===
    

    the content of btick.txt files:

    btick1 `def`