Home: Perl Programming Help: Regular Expressions:
Search and replace help : Perl one liner



jaggims
New User

Dec 7, 2012, 7:55 AM


Views: 14509
Search and replace help : Perl one liner

hi i am trying to use perl oe liner to search old cell names and replace with new cell names in many category files, but some how it doesnt work, could be there is a special character in between.

see the below example

category.file

esd_gold/cellName1 type="cell"
esd_gold/cellName2 type="cell"
esd_gold/cellName3 type="cell"
esd_gold/cellName4 type="cell"
esd_gold/cellName5 type="cell"
esd_gold/cellName5_temp type="cell"


i am interested to replace only cellName* with new cell names (say cellnameA cellNameB cellNameC cellNameD & cellNameE, for this i am using below onle liner but it doesnt work when the part of a cell name repeats multiple times it goes wrong.

perl -p -i -e 's/$existing_string/$replacing_string/g' category.file


Laurent_R
Veteran / Moderator

Dec 7, 2012, 10:12 AM


Views: 14499
Re: [jaggims] Search and replace help : Perl one liner


In Reply To
perl -p -i -e 's/$existing_string/$replacing_string/g' category.file


If you use this one-liner, this cannot work, since the $existing_string and $replacing_string variables have not been defined anywhere in the script, so that the script does know what you want to match and by what you want the matched pattern to be replaced.

Actually, I don't know either what you want to replace by what. You don't give enough information for us to help you.

If you said something like "I want to replace 'cellName5' by 'Cell_name5'", I would immediately know what to suggest. But, here, we don't really know.


BillKSmith
Veteran

Dec 7, 2012, 12:58 PM


Views: 14494
Re: [jaggims] Search and replace help : Perl one liner

This probably is not sufficiently general, but it does what you ask for;

Code
use strict; 
use warnings;
my @suffixes = qw( _ A B C D E);
while (<>) {
s/(cellName)(\d)/$1$suffixes[$2]/;
print;
}

Good Luck,
Bill


jaggims
New User

Dec 10, 2012, 4:56 AM


Views: 14415
Re: [Laurent_R] Search and replace help : Perl one liner

Hi,

basically i want to find a reg-exp to search and replace a whole word, i use below option, but it doesnt work
system("/usr/local/bin/perl -p -i -e 's/\b$existing_string\b/\b$replacing_string\b/g' /remote/de02h26/jmuddaia/tmp_esd_gold/USB_unique.Cat_copy");


Laurent_R
Veteran / Moderator

Dec 10, 2012, 10:41 AM


Views: 14405
Re: [jaggims] Search and replace help : Perl one liner

If I understand you well, you're trying to launch a Perl one-line script from a Perl program, using the system function.

Why, for god's sake, would you want to to that? You can do directly in your Perl program everything that you want to do in the one-liner. Unless your favorite motto is: "why should we do things simple when they can be made complicated?"...

Just read the file in tour perl program and do the changes you need.