[lug] using sed.

rm at mamma.varadinet.de rm at mamma.varadinet.de
Mon Nov 6 04:42:14 MST 2000


On Mon, Nov 06, 2000 at 12:15:56PM +0100, Detlef Brendle wrote:
> hi folks 
> I m not a unix crack  and I just cant figure out why it doesnt work..
> here is what I need todo.
> 
> a - search a pattern (say "blank") within files located in this folder and below.
> b - replace the pattern found (if there is any) with a new text say "blank extended" (this extension should be put into the file as parameter - so I can adjust the new string as I need it.
> c - replace the old file with the file holding the new changes.
> 
> doesnt that sound pretty easy to u folks ?
> its not for me ;(

Does it need to be sed? It could be easily done in perl ...

As a perl program you might start like this:

#!/usr/bin/perl


while (<>) {                     # <> is perl magic, it'll 
                                 # read lines from std. input
		                 # or from file(s) given as arguments
                           
  s/(blank)/${1}extension/go;    # substitute pattern with
  print;                         # pattern + extension.
}

exit 0;            

Ok, that's an o.k. start, but we can do it easier.
Perl has a handfull of commandline switches that
make short scripts like the above even shorter (try
'perl -h' or 'man perl'). The '-p' switch wraps
a  'while (<>) {[your script here]; print}'
arround your script. So we get the following:

  perl -p -e 's/(blank)/$1.extension/og;' dir/*

Ah, but we want to substitute 'in place', so
we need the '-i' switch as well:

 perl -pi -e 's/(blank)/$1.extension/og;' dir/*

But what happens if we change our mind or have
a typo? The '-i' switch takes an optional
parameter, the extension that should be added
to backupfiles (if you don't give an extension
there won't be any backup files!):

 perl -ip .bu -e 's/(blank)/$1.extension/og;' dir/*


Ralf




More information about the LUG mailing list