I have a file with the below content. I want to replace chrome with chromeBackup but not in all places.

Run=bin -app "chrome/chrome.sh"

Required output:

Run=bin -app "chromeBackup/chromeBackup.sh"
  • 1
    Can you describe the places that should and should not be replaced? – Jeff Schaller Mar 14 at 17:24
  • Check my "required output" – Nani Mar 14 at 17:27
  • A good answer would operate on any input; otherwise, someone could just statically print your desired output. – Jeff Schaller Mar 14 at 17:38
  • 2
    In other words, one possible answer right now would be two tell you to open an editor and make the changes manually. – Jeff Schaller Mar 14 at 17:39
  • 1
    Your required output doesn't really clarify your desired behavior. Do you want the change only on lines that start with Run= or Vol.apps? Every line except ones that start with Name=? Only lines that contain a "p"? Something else? – Kevin Mar 14 at 19:34

According to the information you have provided, you want to replace it at two places, so you can use:

sed -e /^Run/s/chrome/chromeBackup/g -e /^Vol/s/chrome/chromeBackup/g file_name


As @Kusalananda mentioned in his comment, shorter version is:

sed -E '/^(Run|Vol)/s/chrome/&Backup/g' file_name
  • 4
    Or possibly sed -E '/^(Run|Vol)/s/chrome/&Backup/g'. – Kusalananda Mar 14 at 18:35

More general perhaps, change all instances except those on the line starting Name=

from="chrome"; to="${from}Backup"; sed "/^Name/! s/$from/$to/g" fileToChange

or just skip the first line

from="chrome"; to="${from}Backup"; sed "2,$ s/$from/$to/g" fileToChange

or only in the lines starting Run or Vol

from="chrome"; to="${from}Backup"; sed -E "/^Run|^Vol/ s/$from/$to/g" fileToChange

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.