Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search and replace using a specific pattern 2

Status
Not open for further replies.

komark

Technical User
Sep 12, 2005
134
US
Hi,

I am trying to search and replace in a file. I am trying to look for the word: foo in every line:

foo f1 f2 f3.....

and replace it with:

foo f1 new_word f2 f3...

I think i'm close with the following line of code but not quite there yet:
$line =~ s/^foo(\s)*/.foo(\s)*new_word/;

Thanks in advance!
Omar.
 
Based on the sample data you provided, you're close! Try something like:
Code:
$line =~ s/(foo \S+)/$1 new_word/
 
Try:

Code:
$line = s/^(foo\s+\S+)/$1 new_word/

(foo \s+\S+) captures "foo", the spaces and word following foo, and $1 inserts the captured string into the replacement string.

Annihilannic.
 
Thanks Annihilannic - it worked.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top