I've been trying to improve my understanding of unicode, and wanted to make a script to take a unicode character as $ARGV[0] and search thru all directories and files, looking for that character in either the filename itself, or it's file contents.

I know there are various unicode perlrun options, but I've found I didn't need it. My .bashrc is set to use en_US.UTF-8.

I'm using Perl 14.1, and this seems to work well. If any unicode experts have a way to simplify the code, especially to avoid using decode(), please speak up.

Just run the script with a string containing a unicode character, like ./script 本 and it will recursively search and report all directories or filenames with that string in it's name, and also search thru every file regardless of name for the string in it's content.

#!/usr/bin/perl use warnings; use strict; use File::Find; use Encode qw(decode); my $path = '.'; # use utf8::all or use the commented lines beneath use utf8::all; # use this instead of the utf8::all module # make input strings utf8 #$_ = Encode::decode('UTF-8', $_) for @ARGV; # make STDIN STDOUT STDERR to be utf8, #binmode STDOUT, ':encoding(UTF-8)'; #binmode STDIN, ':encoding(UTF-8)'; #binmode STDERR, ':encoding(UTF-8)'; my $search_str = $ARGV[0] or die "need a search string\n $!\n"; print "search-> $search_str\n"; my $regex = qr/\Q$search_str\E/; print "regex-> $regex\n"; # finds all files with $regex in it's filename # and all files who have a line matching $regex find (sub { # make File::Find unicode $_ = decode('utf8',$_); $File::Find::dir = decode('utf8', $File::Find::dir); if ($_ =~ /$regex/){ # check for name match if( -d ){ print "dirname match: $File::Find::dir/$_\n" }else{ print "filename match: $File::Find::dir/$_\n" } } # now check filename's contents my $filename = $_; # avoid $_ confusion # the following line is not needed with utf8::all, # otherwise use the following #open (my $fh,'<:encoding(UTF-8)', $filename); open (my $fh,'<', $filename) or warn "Can't open $filename +$!\n"; while(<$fh>){ if ($_ =~ /$regex/){ print "text match in $File::Find::dir/$filename: $_\n"; } } }, $path);

I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku ................... flash japh

Replies are listed 'Best First'.
Re: UTF-8 and File::Find
by Corion (Patriarch) on Jun 30, 2012 at 16:02 UTC
    # make File::Find unicode $_ = decode('utf8',$_);

    ... of course, this assumes that your file system encodes all non-ASCII filename entities as UTF-8. If your filesystem does not do that (like, say, FAT32, or directories mounted via Samba, or HFS+ filesystems) then your script will not return the correct results for these files.

    HFS+ encodes filenames as NFD, so you'll likely have to convert them to NFC for comparisons to work properly.

      Thanks for pointing that out, I don't deal much with network filesysytems. :-)

      I'm not really a human, but I play one on earth.
      Old Perl Programmer Haiku ................... flash japh