Reputation: 349
I'd like to grep text in files using perl regexp and I do that
find ./ -name *.php -print | xargs perl -nle '/standard/ and print $0'
As I found (using google) in the $0 must be the name of executed script, but it contains "-e". How can I get executed scriptname?
Upvotes: 0
Views: 339
Reputation: 265221
Do you want to list all php files, which contain the string standard
? If so, I would use grep -r
:
grep -r -l 'standard' . | grep '\.php$'
As stated in my comment to your question, there is no script name, because you are not executing a script file. Assuming you want to print the filename which is passed to xargs/perl, use See TLP's answer instead$ARGV[0]
to get the first positional parameter to the perl invocation (xargs automatically appends it to the command line).
You should also use find -print0 | xargs -0
to handle files with newlines correctly.
Extending the grep snippet: It's also possible to use grep inside a new shell, after filtering with find:
find . -name '*.php' -print0 | \
xargs -0 -L1 sh -c 'grep -l "pattern" "$1"' -
xarsg -L1
to only pass a single file name at once to the new shell. grep -l "$1"
to print the file name and stop grepping after the first match. -
as first parameter to sh is necessary so that $1
will work.
Another edit …
I was thinking way to complicated. The last command can easily be simplified to:
find . -name '*.php' -print0 | xargs -0 grep -l "pattern"
This of course is not as easily extendable as the sh -c
version, which can pretty much do anything.
Upvotes: 2
Reputation: 39158
Programmers substitute long find/grep command-lines with ack. It uses Perl regex, which are more advanced than GNU grep with -P
(PCRE) or whatever gimped implementation of regex POSIX grep uses.
ack --php -l '(?<!\$)standard'
-l
prints the matching file names only.Upvotes: 5
Reputation: 67900
I assume what you want is to print the file name. If so, use $ARGV
.
perl -nle '/standard/ and print $ARGV'
From perldoc -v '$ARGV'
$ARGV contains the name of the current file when reading from <>.
The -n
switch does just this, it puts a while(<>)
loop around the program.
However, this will print file names once for each match. If you want to print only once, you can close the file handle, ending the loop for that file.
perl -nle 'if (/standard/) { print $ARGV; close ARGV; }'
Upvotes: 2