sed search/replace for NOT string value in line
techAdmin
Status: Site Admin
Joined: 26 Sep 2003
Posts: 4127
Location: East Coast, West Coast? I know it's one of them.
Reply Quote
I finally found a way to do NOT containing string edits with sed, thanks to tdistler.com

I had always tried some way to use the ! not operator in sed, but I had never found the right way to do it. The example below also includes some find stuff, which isn't relevant for the core application of replace where not string, but I'll leave it as is for now.

:: Quote ::
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.


To make it clear:
to delete a line that does NOT contain a string, do this:
:: Code ::
sed -i ‘/STRING_TO_INGORE/! { d }’

and to edit a line NOT containing string, do:
:: Code ::
sed -i ‘/^[ \t]*\/\/.*/! { s/STRING1/STRING2/ }’


The second part, in the {}, can be any normal sed I believe, though I haven't tested it for real regex, ie, for gnu sed, sed -r
Back to top
Display posts from previous:   

All times are GMT - 8 Hours