question: text substitution using Perl

Kevin D. Clark kclark at elbrysnetworks.com
Fri Oct 20 17:03:54 EDT 2006


Zhao Peng writes:

> ********substitution 1************
> The characteristic of original string:
> 1, always start with "$"
> 2, then followed by an integer, could be more than 1 digit, such as 23
> 3, always end with a period "."
> 4, there is always a blank before & after original string
> For example: $2.
>
> The characteristic of target string: always has "ebcdic" inserted into
> the original string between "$" and the integer
> For example: $ebcdic2.
>
> So the substitution will look like this
> $2.  ->  $ebcdic2.
> $67.  ->  $ebcdic67.
>
> Should the regular expression for original string be: \$\d+\.   ?

Looks pretty much right to me.

I would make this replacement like this:
 
  s/ \$(\d+)\. / \$ebcdic${1}. /g;

The ${1} in there is something called a "backreference".

The 'g' at the end of the line generally specifies "do this as many
times as possible on each line".


> ********substitution 2************
> The characteristic of original string:
> 1, always start with an integer, could be more than 1 digit, such as 23
> 2, then end with a period "."
> 3, there is always a blank before & after original string
> For example: 2.
>
> The characteristic of target string:
> always has "s370ff" added to the beginning of original string
> For example: s370ff2.
>
> So the substitution will look like this
>
> 2.  ->  s370ff2.
> 14.  ->  s370ff14.
>
> Should the regular expression for original string be: \d+\.   ?

I would make this replacement like this:
 
  s/ (\d+)\. / s370ff${1}. /g;


> My real situation is that I have a bunch of files at one directory, of
> which for the files whose name contained "readme",  I need to do 2
> substitutions described above.

One way to quickly do this might be like this:

  perl -i.bak \
       -pe 's/ \$(\d+)\. / \$ebcdic${1}. /g;
            s/ (\d+)\. / s370ff${1}. /g;'     \
       your-directory-somewhere/*readme*


This in itself makes a backup for you, but you might want to make your
own backup files beforehand.

Just another Perl hacker,

--kevin
-- 
GnuPG ID: B280F24E              Never could stand that dog.
alumni.unh.edu!kdc                   -- Tom Waits



More information about the gnhlug-discuss mailing list