#! /usr/bin/perl use strict; use warnings; # $ERRNO instead of $! amongst other stuff use English qw( -no_match_vars ); my $path = "./IN/"; my $string = 'ABC'; my @filesWithString; opendir my $dh, $path or die "Can not open $path: $ERRNO"; FILE: while (my $file = readdir $dh) { # ignore 'hidden' files and ., .. if ($file =~ m/^\./) { next FILE; } # opendir and this should be replace with File::Find # makes relocationg the perl script to a different directory # much easier my $filename = $path . $file; # always check return value for open, close open my $fh, '<', $filename or die "Can not open '$filename': $ERRNO"; # keep track of current line number for nice message my $linecount = 1; LINE: while (my $line = <$fh>) { # encase $string in \Q \E in case it contains regexp metacharacters # (remove this if you actually want to use metachars) if ($line =~ m/\Q$string\E/) { print "Found string '$string' in file $filename (line $linecount)\n"; push @filesWithString, $filename; # abort all further parsing - we already found the string last LINE; } $linecount++; } close $fh or die "Can not close filehandle for '$filename': $ERRNO"; } closedir $dh or die "Can not close $path: $ERRNO"; for my $file (@filesWithString) { my $newName = $file . '.ABC.txt'; print "Renaming $file to $newName\n"; # uncomment this after debugging / verification #rename $file, $newName; }