See also my recent Re: *SAFE* use of string in system command for safe use of filenames.
Use %ENV and the old standby of adding /dev/null to force grep to print filename**s**. That way names containing quotes and worse won't create a mess.
# note that a simple pure perl version using 3arg open and # e.g. $count=$contents=~s/$argument/$&/g will have # about the same code length; besides offering way more # **cute** regexes... $ENV{file}=$file; # protect filename from shell interpolation $ENV{argument}=$argument; # also protect non-trivial regexes from shel +l! # upd: either -H OR /dev/null, sigh. a very telling misread of mine $results=`grep -c -H "\$argument" "\$file"`; # /dev/null`; # note \$ i +nstead of \"
Above is as usual incomplete and a bold lie: the reporting with still suffer in case of an embedded but unfiltered \n being a part of the filename (UTF-8 probably also offers some more interesting whitespace to play with; names with terminal esc sequences are also fun in print, warn & die). But especially \n really warants IMAO a cronjob and a shoot-and-kill policy for both file and file creator upto and including layer 8.
cu
Peter
1. of course, this (unnecessary) last minute addition of /dev/null belongs before the closing `-quote, just as your first parsing error indicated. Sorry & fixed above.
2. Oops: you need to move down the $ENV{file} (in your example below) into the first foreach loop. The $ENV{argument} similar after $argument has been assigned to, into the second loop, or better yet, trading efficiency to readability, both just before the grep.
3. ok, compare your version with the full working one here and do check the comments:
#!/usr/bin/perl -w #this file is for grepping within vdx files, and outputs the following +: #filename:<#of hits>:<arguments> #filename:2:myargument open ARGUMENTS, "<","file"; @files = <*.vdx>; @arguments = <ARGUMENTS>; foreach $file (@files) { #$copyfile="\"".$file."\""; foreach $argument (@arguments) { chomp $argument; #print "$copyfile\n"; # 0. move these _down_ to here ($ENV{f},$ENV{a})=($file,$argument); # 1. consider egrep instead for a bit more readable posix regexes # 2. two ways to make grep include file names: the newish -H or # the classic /dev/null trick (the last second change was also a la +st # check misread your opening to imply missing _file_ argument :/) $results=`grep -H -c "\$a" "\$f"`; # /dev/null`; # 3. do you really want to see non-match reports? $rc=$?; next if $rc; # nothing to report # 4. but gnu grep ... /dev/null now insists to sumarize non hits as we +ll # $results=~s/\n.*//sgo; chomp $results; print "$results:$argument\n"; } }
In reply to Re: Perl backticks and GREP?
by jakobi
in thread Perl backticks and GREP?
by symgryph
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |