IslandPatrol IslandPatrol - 1 month ago 6
Linux Question

How to replace a string in a file only if the line containing it does not also contain a specific string using Bash?

I would like to replace all instances of

target
with
replace
in the following file.csv using Bash, but only if the line containing it does not also contain the string
skipline
:

file.csv:

abc,abc,keepline,target,abc,abc
abc,abc,skipline,target,abc,abc


Desired output:

abc,abc,keepline,replace,abc,abc
abc,abc,skipline,target,abc,abc


I am attempting to use
sed
:

sed 's/target/replace' file.csv > newfile.csv


How can I include logic to check each line for the string
skipline
?

Answer
% sed '/skipline/!s/target/replace/g' input
abc,abc,keepline,replace,abc,abc
abc,abc,skipline,target,abc,abc

In sed you can specify where to substitute: /foo/ searches for foo, 1,5 means from line 1 to 5. A ! inverts that search.

Comments