Skip to content
Advertisement

SED one liner to uncomment and replace first occurrence of a pattern

I have this settings.conf file in linux defined as follows:

Section A
  first-setting = value
#  second-setting = off
  third-setting = value

Section B
  first-setting = value
#  second-setting = off
  third-setting = value

I would like to uncomment # second-setting = off of Section A only (first occurrence), and set the value to on.

So far, I have this:

cat settings.conf | sed '/^# second.*/ {s/^#//;s/off/on/}'

Any tips?

Advertisement

Answer

Is this what you had in mind?

sed '0,/#/s/#(.*) off/1 on/' settings.conf

Or if your on osx with non-gnu sed:

sed '1,/#/s/#(.*) off/1 on/' settings.conf
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement