sed double expression: match, replace in one line, overwrite file
Posted by jpluimers on 2020/04/15
A while ago, I needed to conditionally replace in files, so I used sed
and a regular expression
, though usually I dislike those.
However, since the system had a very basic install, there was not much choice.
Luckily back then, my Google foo returned these:
- [WayBack] sed 102: Replace In-Place Replace files in-place with sed’s
-i
flag. - [WayBack] Unix Sed Tutorial: Find and Replace Text Inside a File Using RegEx
This allowed me to do a double expression (the first matches a pattern, the second performs the actual replacement within the matching lines).
In case my Google foo in the future fails:
## https://robots.thoughtbot.com/sed-102-replace-in-place
## -i causes no backup to be saved, but does in-place replacement
## since we run under git, we can always restore
## combined with a double expression (the first matches, the second executes) this is very powerful
sed -i -e '/#.*AVOID_DAILY_AUTOCOMMITS=.*$/s/^.//' /etc/etckeeper/etckeeper.conf && git diff | more
–jeroen
Leave a Reply