Quintin Par
Quintin Par

Reputation: 16252

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?

Upvotes: 5

Views: 2356

Answers (2)

Barton Chittenden
Barton Chittenden

Reputation: 4416

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.

Upvotes: 4

Dennis Williamson
Dennis Williamson

Reputation: 359905

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.

Upvotes: 7

Related Questions