1

My intention is to search for a string in specific file format recursively in the current directory. From SO I found this find command to search

find . -type f -name '*.extension' | xargs grep -i string

But this was too lengthy and I found this really hard to remember. So, I tried to write a function and add it to my .bash_profile something like this

function search {
     echo `find . -type  f -name '*.$1' | xargs grep -ir '$2'`
}

and the other one which I've tried is

function search {
    echo `find . -type  f -name '*.$1' | xargs grep -ir '$2'`
}

Both didn't print any results on the screen when I invoke my as

search txt mysearchstring though I have few .txt files in the directory which contains the word mysearchstring. I'm not sure what makes me go wrong. Can someone help me on this?

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
  • double quote `$1` and `$2` – Inian Nov 22 '18 at 04:47
  • @Inian: Thanks for the suggestion Inian. It worked but it didn't preserve the new line character which `grep` provides. It presents entire result in a single line. – Tom Taylor Nov 22 '18 at 04:50
  • 3
    You don't need to `echo` inside the function (remove it), just have the `find` command alone. It will print its standard output to terminal – Inian Nov 22 '18 at 04:51
  • Hurrah !! It worked thanks @Inian. – Tom Taylor Nov 22 '18 at 04:53
  • 2
    BTW, you can simplify the `find ... | xargs grep ...` sequence with `find`'s `-exec` primitive: `find . -type f -name "*.$1" -exec grep -ir "$2" {} +`. This also avoids parsing trouble with some weird characters in filenames. – Gordon Davisson Nov 22 '18 at 06:12
  • Wow that sounds cool ! Thanks @GordonDavisson :) – Tom Taylor Nov 22 '18 at 07:06

0 Answers0