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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With