Easy fixes using perl

By  

This isn't going to be useful to you if you're using an extended character set.

$string =~ tr/\x80-\xFF//d;

Removing carriage returns

When using perl, the expression \r represents a carriage return while \n is a linefeed. You can easily remove carriage returns from a string variable as shown below.

$str =~ s/\r//g;

Carriage returns and linefeeds are removed by combining \r and \n in that order, of course, since that's the order in which they appear in text files, like those that are created on Windows systems.

$str =~ s/\r\n//g;

This one-liner removes carriage returns in a file using the same logic:

perl -p -i -e 's/\r//g' dosfile

This can be especially handy if you don't have a tool like dos2unix available. Plus, I really like the "in place" (no temporary files or copies involved) nature of perl commands with the "pie" (-p -i -e) arguments. And it easily turns into an alias:

alias rmCR='perl -p -i -e '\''s/\r//g'\'''

Adding line numbers

To add line numbers to the contents of a file, try this:

perl -p -i -e '$_ = "$. $_"' myfile

This one takes a bit of explanation. The $. variable contains the line number, so the command reads "change the line to the line preceded by the line number".

Replacing text

Perl pie commands make replacing text within a file fairly easy, though you should always be careful that you're not changing text you didn't mean to change along with the text you hoped to target.

perl -p -i -e 's/2011/2012/g' filename

Renaming files

This command renames files to their lowercase character equivalents. Read this as "for every argument provided (i.e., the file list "*"), rename the file to lowercase unless a file by that name already exists".

perl -e 'for (@ARGV) { rename $_, lc($_) unless -e lc($_); }' *

And, of course, you could do the same thing with uppercase by replacing lc with uc in both
locations.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question