0

I run the following command to search for text in files and display a pretty output:

$ grep -rnI "SEARCHTERM" . | sed 's/\:\s\+/\:\n/g'
./path/filename.php:LINENUMBER:
This line contains SEARCHTERM

But when I try to run it as an alias I get an error:

$ alias lookfor="grep -rnI '\\!^' . | sed 's/\:\s\+/\:\n/g'"
$ lookfor SEARCHTERM
sed: can't read SEARCHTERM: No such file or directory

Any thoughts as to why my alias is failing? I'm sure it's some sort of quoting issue...

Thomas Hunter II
  • 5,081
  • 7
  • 35
  • 54

2 Answers2

2

Bash (annoyingly, IMHO) doesn't support arguments for aliases. Instead, I'd suggest writing what you want as a function instead (which are much more powerful):

lookfor() {
  grep -rnI '\\!^' "$@" | sed 's/\:\s\+/\:\n/g'
}

Functions in the long run are better anyway... They'll let you expand it for error handling, etc, later if you like.

Wes Hardaker
  • 21,735
  • 2
  • 38
  • 69
  • What is the "$@" for? Does it equate to $PWD in the .bashrc? Also, this script does not seem to be working (It keeps waiting for the search path to be given) when I do something like this instead: function igrep() {grep -r $1 "$@" | grep -v ".svn";} – Arpith Oct 19 '12 at 06:51
  • The `"$@"` stands for "replace with all the arguments given to the command". Because the `$@` is in quotes, it also means "properly quote each one if it needed quoting". EG, if you typed `lookfor "foo bar" baz`, the `"foo bar" baz` (including quotes) would be passed to the grep command. (it's slightly more complex in implementation, but you can still think about it this way). – Wes Hardaker Oct 19 '12 at 13:32
0

I ended up creating a ~/bin folder, and placing an executable file in there named lookfor, with the following content:

#!/bin/sh
grep -rnI "$1" . | sed 's/\:\s\+/\:\n/g'

The ~/bin folder is already acknowledged by my distro as being in the PATH, but for those who don't have this automatically set, you can add it to your PATH by putting the following in your ~/.bashrc:

if [ -d ~/bin ] ; then
    PATH=~/bin:"${PATH}"
fi
Thomas Hunter II
  • 5,081
  • 7
  • 35
  • 54