Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find throw paths must precede expression in script

I am trying to alias find and grep to a line as show below

alias f='find . -name $1 -type f -exec grep -i $2 '{}' \;'

I intend to run it as

f *.php function

but when I add this to .bash_profile and run it I am hit with

[a@a ~]$ f ss s
find: paths must precede expression
Usage: find [-H] [-L] [-P] [path...] [expression]

How do I resolve this?

like image 824
Quintin Par Avatar asked May 22 '12 23:05

Quintin Par


2 Answers

Aliases don't accept positional parameters. You'll need to use a function.

f () { find . -name "$1" -type f -exec grep -i "$2" '{}' \; ; }

You'll also need to quote some of your arguments.

f '*.php' function

This defers the expansion of the glob so that find performs it rather than the shell.

like image 86
Dennis Williamson Avatar answered Oct 31 '22 15:10

Dennis Williamson


Expanding on Dennis Williamson's solution:

f() { find . -name "$1" -type f -print0 | xargs -0 grep -i "$2"; }

Using xargs rather than -exec saves you from spawning a new process for each grep... if you have a lot of files, the overhead can make a difference.

like image 4
Barton Chittenden Avatar answered Oct 31 '22 13:10

Barton Chittenden