Comment all lines which are not already commented for each full path pattern matched

Hello.

Question 1 :

I want to comment out all lines of a cron file which are not already commented out for each full path pattern matched.

Example 1 nothing to do because line is already commented out; pattern = '/usr/bin/munin-cron'

# */5 * * * *     munin test -x /usr/bin/munin-cron && /usr/bin/munin-cron

Example 2 line is being commented out; pattern = '/usr/bin/munin-cron'
before :

*/5 * * * *     munin test -x /usr/bin/munin-cron && /usr/bin/munin-cron

after :

# */5 * * * *     munin test -x /usr/bin/munin-cron && /usr/bin/munin-cron

I have tried this but it is not working :

sed -i '\|/usr/bin/munin-cron\| s|^|#|' /etc/cron.d/munin

Got error :

sed: -e expression #1, char 27: unknown command: `^'

Question 2

And the reverse command
I want to uncomment all lines of a cron file which are not already uncommented for each full path pattern matched.

Example 1 nothing to do because line is already uncommented ; pattern = '/usr/bin/munin-cron'

*/5 * * * *     munin test -x /usr/bin/munin-cron && /usr/bin/munin-cron

Example 2 line is being uncommented ; pattern = '/usr/bin/munin-cron'
before :

#*/5 * * * *     munin test -x /usr/bin/munin-cron && /usr/bin/munin-cron

or before :

# */5 * * * *     munin test -x /usr/bin/munin-cron && /usr/bin/munin-cron

after :

*/5 * * * *     munin test -x /usr/bin/munin-cron && /usr/bin/munin-cron

Any help is welcome

You escaped one address delimiter too many. man sed :

Try your sed command again, with the second | unescaped.

To avoid commenting out an already commented line, you can either add the # to all matching lines, and then remove duplicates, or extend the address, like

sed '\|^[^#].*/usr/bin/munin-cron| s|^|#|' file

Using a similar address for the reverse operation, including 0 - n spaces in the s command, is left as an execise for the reader.

2 Likes

Thank you very much.

What is the meaning of : ^[^#] in '\|^[^#].*.................

It is a "bracket expression" at begin-of-line ("^", as you used it in your substitution). man regex :

1 Like