Artificial intelligent assistant

sed replace with exception list I need to replace strings in many large textfiles but I have a list of exception strings (200+ items). For example: # I want to replace every "dank". Except when it comes in the following form: dankine dankzwd nudankip dankphys danko.mod ... (The list is 200+ items long) My current regex looks like this: sed -e "s/dank/monk/g" /path/to/file The content of the file looks like this: xdankine redankus dankzwd danke dankbe testdank this is the content of the file after execution: xmonkine remonkus monkzwd monke monkbe testmonk But I want the content to look like this: xdankine remonkus dankzwd monke monkbe testmonk since dankine and dankzwd are in my exclusion list. The file can contain more than one possible replacement per line. How can I accomplish this?

So as not to overload the regex since the exclusion list can be 200+ strong, we first generate the sed code using the exclusion list file and apply that generated code on the data input.

GNU sed


sed -e '
1i\
s/dank/\\
/g
h;s:[\&/]:\\&:g
x;s/dank/\
/g
s:[][^$\/.*]:\\&:g
s/\
/\\
/g;G
s:\
:/:;s:.*:s/&/g:
$a\
s/\\
/MONK/g
' excludes.txt | sed -f - file


* * *

Output:-


xdankine reMONKus
dankzwd
MONKe MONKbe
testMONK


* * *

Proof of concept:-

* First off, turn all danks to literal newlines, a char guaranteed not to be found.
* Then turn a line in exclude list like `nudankip` to as given below and likewise for all lines in exclude list.
* `s/nu\
ip/nudankip/g`
* The complexity is due to the fact that we need to escape the exclude list fir the rhs and lhs of a sed s/// expression.

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy e3c1879d82806be60204d596a436cd32