Posts Tagged regular expression

LCOD – 2.18.07 – Simple command line perl substitutions

Ever have a list of things that you want to change all the same? Say you have an image directory and you want to make an html list of all the images in your directory? Perl to the rescue!

first, make a file that lists all the images (we’re using *jpg, but you could do *gif, or *coolimages*, or just * for all files in the dir – note: all files in dir * with a redirect will catch the file you are redirecting to, and it will likely need to be removed)

From the shell / command line, run:

/bin/ls *jpg > ourfiles

Now the fun part! This will take a line like this

picture1.jpg

And make it look like this
<a href=”picture1.jpg”><img src=”picture1.jpg” border=”0″></a>

From the shell run / command line, run:

perl -pi -e ‘s/^(.*)$/<a href=\”$1\”><img src=\”picture1.jpg\” border=\”0\”><\/a>/’ ourfiles

The basic pattern of this command is

‘s/SEARCH PATTERN REGEX/REPLACEMENT PATTERN/’

The search pattern is a Regular Expression, and the Replacement Pattern needs to have any special characters escaped (including / $ # @ “) with a \

The Search Pattern we’re using is a simple one ^ for start of line, (.*) for . anything and * any number of times, with paranthesis around it to put it into the perl variable $1, and $ for end of line.

, , , , ,

No Comments

Easy AdSense by Unreal