.bashrc function implementing grepall

178 views Asked by At

I have 2 bash functions catall and grepall

catall works fine, catting every file it finds with the file name printed first, then the content and a new line

catall ()
{
  find . -name $1 | xargs -I % sh -c 'echo %; cat %; echo"" '
}


grepall ()
{
  find . -name $1 | xargs -I % sh -c 'echo %; cat % | grep $2; echo"" '
}

But grepall doesn't work, is should do the same as catall but with a grep stage on the content of the file

Why is $2 not sub'ed

Can you make this grepall work ?

1

There are 1 answers

3
anubhava On BEST ANSWER

It is because you are forking a new shell process using sh -c and all the variable of parent shell are not available in child shell unless you export them.

Use this function to make it work:

grepall () {
   export p="$2"; find . -name $1 | xargs -I % sh -c 'echo %; grep "$p" %; echo "" ';
}

It works now because we are creating an exported variable p which becomes available in sub shell also.

Since you are forking a new shell anyway you don't really need to call xargsa as find can do the job for you:

grepall () {
   export p="$2"; find . -name $1 -exec sh -c 'echo $1; grep "$p" $1; echo "" ' - {} \;;
}