File search using regex

Chris Foote chris at inetd.com.au
Thu Apr 19 11:41:35 CST 2007


On Thu, 19 Apr 2007, Mark Newton wrote:

> Chris Organ wrote:
>
>> Wondering if someone can assist with regex searches using perl / grep / 
>> anything command line. I have lost a severe amount of hair looking for a 
>> multi-line search based on exact pattern matching. What I need to do is 
>> find this exact header within files within a directory and list them, 
>> similar output to using grep -l  ie a list.
>
> All you wordy python programmers are weenies.  What ever happened to
> efficient code, I ask you?  Sheesh!

hehe... Perl's grep function is good.

This is close:

#!/usr/bin/python
# usage: search.py files...
import sys, re

pattern = re.compile(r'\n?!D2\nInvoice\n!C\nAUSTALIA EIGHT')
print '\n'.join([f for f in sys.argv[1::] if pattern.search(file(f).read())])


> #!/usr/bin/perl
>
> # usage:  search.pl filespec
> # (filespec can be a list of files, wildcard, etc...)
>
> local $/;
>
> map {
>    open FH, "<$_";
>    print "$_\n" if grep (/^!D2\nInvoice\n!C\nAUSTALIA EIGHT/, <FH>);
>    close FH;
> } @ARGV;
>
> # end

-- 
Chris Foote <chris at inetd.com.au>
Inetd Pty Ltd T/A HostExpress
Web:   http://www.hostexpress.com.au
Blog:  http://www.hostexpress.com.au/drupal/chris
Phone: (08) 8410 4566


More information about the linuxsa mailing list