regex - grep/ack on Mac OS X finding multiple strings and respecting file types -
i run grep on mac os x meeting following criteria:
- search files
*.ror*.rextension , ignore other files - find strings:
worda,wordbaccounting fact strings may appear in formatsomerubbishwordarubbish(this valid match) - list files both strings appear irrespectively of order
- print lines strings appear
- highlight found words in colour
- print file name header , lines under header. i'm inspired
ackoptions. - ignoring case
approach
i thinking of making use of this discussion , starting following grep syntax:
grep --include=*.r -r setheader . then combining following:
grep 'word1\|word2\|word3' /path however, appreciate comments on ensuring of criteria stated above evaluated correctly.
groups
^(.*)(facet|map)(.*)(map|facet)(.*)$ ack
running ack -f shows *.r files searched solutions using ack accepted. example, running:
ack worda --colour -i -h --rr gets desired results respect worda. thinking of combining solutions discussed here use and not or , ignore order in strings may appear. further tried:
ack --match worda --match wordb --colour -i -h --rr but produced results wordb.
here's script combines closely-named awk , ack commands:
find . -iname '*.r' | while read file; awk ' begin { ignorecase=1; sawworda = 0; sawwordb = 0 } /worda/ { sawworda = 1 } /wordb/ { sawwordb = 1 } sawworda && sawwordb { exit } # stop reading lines if both matches seen end { exit !(sawworda && sawwordb) } ' \ "${file}" \ && ack --nofilter -h -i 'worda|wordb' "${file}" done the awk command...
- lists files both strings appear irrespectively of order
- ignores case
...and ack command...
- prints lines strings appear
- highlights found words in colour
- prints file name header , lines under header inspired ack options
- ignores case
the awk script sets flags if there search string matches. if both strings have been matched, snippet exit !(sawworda && sawwordb) return 0. if awk returns 0, ack command runs.
the ack --nofilter option tells ack avoid reading stdin. otherwise, ack try use stdin read command using.
in comments, konrad asked how use above code when passing in variables in shell script. below example:
#!/bin/sh if [ $# -ne 2 ]; echo usage: $0 {string1} {string2} e_badargs=65 exit $e_badargs fi find . -maxdepth 1 -iname '*.r' | while read file; awk " begin { ignorecase=1; sawarg1 = 0; sawarg2 = 0 } /$1/ { sawarg1 = 1 } /$2/ { sawarg2 = 1 } sawarg1 && sawarg2 { exit } # stop reading lines if both matches seen end { exit !(sawarg1 && sawarg2) } " \ "${file}" \ && ack --nofilter -h -i "$1|$2" "${file}" done the above example doesn't escape special characters in arguments provided script. if escaping needed, script can modified needed.
Comments
Post a Comment