After some digging, I finally found out how to create a regex for Sed (stream editor) that will find a line that does NOT contain a particular string. First, I used ‘find’ to list all the *.cpp files in my source tree:
find . -name “*.cpp” -print
Then I piped the files to ‘sed’ via ‘xargs’ (Note: replace the ‘-e’ with ‘-i’ to actually modify the files inline):
find . -name “*.cpp” -print | xargs sed -e ‘/STRING_TO_INGORE/! { d }’
The trick is adding the ‘!’ (exclamation point) after the search expression. Without it, ‘sed’ would think you only want lines with the string, not without it.
This is different than another syntax I’ve seen used: /(?!STRING_TO_IGNORE)/.
Here’s another example. Say you want to replace STRING1 with STRING2 only if the first characters of the line (ignoring white space) are NOT “//”… i.e. skip the string replacement in code comments:
sed -i ‘/^[ \t]*\/\/.*/! { s/STRING1/STRING2/ }’
NOTE: ‘[ \t]*’ means ignore 0 or more spaces or tabs.


Humm… interesting,
This is really helpful,
Stream editor has never been so easy,
Anyway, thanks for the post,
Keep up the good work,
Reply
Whoa! That (?!) sytnax just saved my life – thanks a lot
Reply
Hi!
I wonder if you can make a script in one line which will cut the part of an input that is bounded by left and right patterns, but if the input doesn’t have this any of the left and right patterns, it will print an empty line.
Thanks,
Reply
Thanks.
Reply