Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/articles/perl-tutorials/)
-   -   A diferent find . -type f -exec grep main {} -H \; (http://www.go4expert.com/articles/diferent-type-f-exec-grep-main-h-t4138/)

oleber 4May2007 22:10

A diferent find . -type f -exec grep main {} -H \;
After allot of searches like 'find . -type f -exec grep main {} -H \;' I implemented a small program :eek:.

;) This program uses the normal 'file' shell command to check if a file is a text file.

;) Ignores files inside /CVS/. They are there, but who cares?

;) Clearly separates the results from different files

and can show how to use:
:cool: the module File::Find
:cool: creating subroutine locally
:cool: the grep, the last, the -f, ...
:cool: get the output from shell commands

Code: Perl

  use strict;
  use warnings;
  use File::Find;
  if (grep {/^-help$/} @ARGV) {
      print "$0 [-all|-file|-help] matchRegExp [path]";
  my $all = grep {/^-all$/} @ARGV;
  my $justFile = grep {/^-file$/} @ARGV;
  my ($match, $initPath) = @ARGV = grep {not /^-(all|file|help)$/} @ARGV;
  die "just one file accepted" if scalar(@ARGV) > 2;
  die "no match" if scalar(@ARGV) == 0;
  $initPath = (".") if not defined $initPath;
  die("unrecognizable path: $initPath") if not -e $initPath;
  my $lastPrinted;
  find( sub {
      my $fileName = $_;
      my $filePath = $File::Find::name;
      return if $filePath =~ m|/CVS/|; # not inside CVS directory
      return if not -f $fileName; # just check files
      return if not $all and `file -b $fileName` !~ /text/i; # just text files
      open(my $FILE, $fileName) or die "canot open file '$fileName': $!";
      while (my $line = <$FILE>) {
          if ($line =~ /$match/) {
              if ($justFile) {
              } else {
                  print("\n", "*"x80, "\n\n")
                      if $lastPrinted and $lastPrinted ne $filePath;
                  $lastPrinted = $filePath;
                  printf("%-50s %s", "$filePath $.:", $line);
  }, $initPath);

A 50 lines program.

shabbir 6May2007 14:24

Re: A diferent find . -type f -exec grep main {} -H \;
Offtopic comment:
By the way nice bullets.

All times are GMT +5.5. The time now is 19:19.