In this example, carriage returns (\r) are removed from all files from a top-level directory down.
File extension exceptions may be entered to exclude certain file types (such as images).
Could be used for several reasons!
#!/usr/bin/perl -w
# Update: Script should now work without generating
# any warnings concering the %skip hash. Thanks to
# jmcnamara for helping with that :)
# This script will remove carriage returns (\r) from
# all files located below a specified parent directory.
# Could be expanded to allow any modifications.
use strict;
use File::Find;
use File::Basename;
####################################
# Configuration
# Directory where recursive modification will begin
my $dir = "/home/username/directory";
# File extensions to skip (ie: images)
# Each entry has the following look:
# 'file extension' => 1
my %skip = (
'gif' => 1,
'jpg' => 1,
'jpeg' => 1,
'png' => 1
);
####################################
# Main Program - No Need To Edit :)
my $count; # Just a counting thing
my @dirs; # All recursed directories
# This does at least 85% of the work!
# It gets a recursive list of all directories
find(\&{
sub {
if (-d "$File::Find::dir/$_") {
if ($count++ == 0) {
push @dirs, $File::Find::dir;
} else {
push @dirs, $File::Find::dir . "/$_";
}
}
}
}, $dir);
# Loop through all directories
foreach my $curDir (@dirs) {
# Get list of files from the directory
opendir DIR, $curDir;
my @files = readdir DIR;
closedir DIR;
# Loop through the files
foreach my $file (@files) {
# Skip directories and "." and ".." entries
# as well as excluded file extensions
my ($nil,$ext) = $file =~ /^(.*?)\.(.*?)$/gs;
$ext = '' unless defined $ext;
next if (-d "$curDir/$file" || $file =~ /^\./ || $skip{$ext});
# Read in the file
open FILE, "$curDir/$file";
my @lines = <FILE>;
close FILE;
# Modify and print the file back
open FILE, ">$curDir/$file";
print FILE map { s/\r//g; $_; } @lines;
close FILE;
}
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|