I would like to find a certain line in a file containing a String "AUTOINSTALL_VTK" and replace in this line the String "OFF" with "ON" using a bash script.

It should be possible to do the replacement with sed but how do I tell sed to only replace "OFF" with "ON" in this one line?


Try this:

sed -i '/AUTOINSTALL_VTK/ s/\<OFF\>/ON/' file

I added word boundaries \< and \> to prevent replacing OFF within some other word, e.g. OFFICIAL.

To run multiple commands for the matching line, you can use { ... }.
Example to switch ON and OFF:

sed -i '/AUTOINSTALL_VTK/{s/\<OFF\>/ON/n;t;s/\<ON\>/OFF/;}' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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