Bash alias request

How to include the following command in a bash alias?

find . -name '*.php' | xargs grep --color -n 'search term' 

Where can I specify the file extension, and the search term is obviously a search query :)

So what I want to do:

  searchFiles 'php' 'search term' 

How to pass input to an alias? Should I just create a bash script and specify an alias for the script?

+4
source share
4 answers

How about using a function? Add this to your .bashrc:

 function searchFiles() { find . -name \*."$1" -print0 | xargs -0 grep --color -n "$2" } 

and then use it like:

$ searchFiles c include

+6
source

You can use an alias, but using a function, as Gonzalo shows, is a reasonable thing.

 alias searchFiles=sh\ -c\ \''find . -name \*."$1" -type f -print0 | xargs -0 grep --color -Hn "$2"'\'\ - 

Whether it is a function or an alias, I recommend using -print0 with find and -0 with xargs. This provides more reliable file name processing (most often, spaces in file names).

+4
source

While the function works, it will not be available for other programs and scripts (without much pain). (The alias would have the same problem.) I would choose a separate script, because it sounds like you want to call it directly:

 #!/bin/bash # since you're already using bash, depend on it instead of /bin/sh # and reduce surprises later (you can always come back and look at # porting this) INCLUDE="*.$1" PATTERN="$2" grep --color -n "$PATTERN" --recursive --include="$INCLUDE" . 

(There is no need to find what you have.)

If it were used only in another script instead of direct, the function would be simpler.

+1
source

Shell functions are good, but you can also take a look at ack . It handles the search on a color-coded file, so your example will be simple

 ack --php somepattern 
+1
source

All Articles