1

I have defined the following alias in ~/.bashrc:

 alias fg='find . -name $1 | xargs grep --color $2'

in order to write

fg "*.txt" " my_text "

and find all file that have extension .txt and contain " my_text " but it does not work. Why?

4
  • 4
    I think that you cannot pass arguments to an alias. Try converting fg to a function instead.
    – sakisk
    Commented Mar 18, 2011 at 9:39
  • 1
    I have an alias --> alias ff='find . | xargs grep $1 -sl' which works fine!
    – Narek
    Commented Mar 18, 2011 at 9:45
  • 8
    fg is a shell builtin, I recommend you chose a different name whether you implement this as an alias or (better still) a function.
    – johnsyweb
    Commented Mar 18, 2011 at 9:53
  • 4
    @Narak, I think your second example there is only working by accident.
    – mattdm
    Commented Mar 18, 2011 at 12:11

3 Answers 3

7

Aliases in bash do not take parameters (as already pointed out), so when you need something like that you can use bash functions (like the one provided by @l0b0).

But what you are trying to achieve here, can be done in a better way by using only grep.

grep -r --color --include="*.txt" " my_text " ./

BTW, fg is a shell built in command, an important one. You should avoid using it as a name for aliases or functions.

EDIT: in a function

$ ffg() { rgrep --color --include="$1" "$2" ./; }
$ ffg "*.txt" " my_text "
1
  • 1
    This assumes GNU grep, of course.
    – johnsyweb
    Commented Mar 18, 2011 at 10:07
3

find ./ -name "$1" -exec grep -l "$2" {} \; should do the trick.

2
  • $i should be $1, and $1 and $2 should be quoted to allow blanks and such in filenames and search-word. Commented Mar 26, 2011 at 12:07
  • Whoops, my bad. Fixed. Commented Mar 26, 2011 at 16:13
0

This works!

function fndg()
{
   find . -name "$1" | xargs grep -rn --color "$2"
}
3
  • find can call grep without xargs invocation, see -execdir, but in this case, the called program grep can iterate itself. Commented Mar 26, 2011 at 12:06
  • xargs will be more efficient, as it will call grep with several filenames at once, instead of one at a time using -exec Commented Mar 26, 2011 at 23:25
  • gnu find can handle mutliple filenames at once too: find . -name "$1" -exec grep --color $2 -- {} + if ended with + instead of ";" Commented Mar 27, 2011 at 19:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .