Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl in-place search-and-replace, but only on lines matching a second pattern

Tags:

regex

perl

Today I learned about how to use perl to do a search-and-replace across one or more files. For example, I can do this:

perl -i -p -e "s/Sydney/Moscow/g" cities.txt

... and after it is done, cities.txt will be modified-in-place, such that all instances of the string "Sydney" have been replaced by "Moscow".

This is great, but I'd like a bit more control: specifically, I'd like the search-and-replace operations to occur only on lines that start with the string "HomeCities:"

For example, if cities.txt looked like this before I ran the command:

HomeCities:   Dublin, Sydney, Los Angeles, Chicago
AwayCities:   New York, Melbourne, Sydney, Oakland

... then after the command completed, it would look like this:

HomeCities:   Dublin, Moscow, Los Angeles, Chicago
AwayCities:   New York, Melbourne, Sydney, Oakland

Is there a way to do this short of writing a script or program with an explicit per-line for-loop and per-line logic?

like image 560
Jeremy Friesner Avatar asked Nov 29 '25 05:11

Jeremy Friesner


1 Answers

You're almost there already:

perl -i -p -e "s/Sydney/Moscow/g if /^HomeCities:/" cities.txt

Edited to add:

By the by, on the off chance that the file could contain a city whose name contains "Sydney" as a substring, eg. "Sydneyville" or something, and you don't want to change it to "Moscowville", you could tighten up the regex to only apply to complete words:

perl -i -p -e "s/\bSydney\b/Moscow/g if /^HomeCities:/" cities.txt
like image 162
Sean Avatar answered Dec 01 '25 22:12

Sean