How to make a line as a comment in SED

2019-03-31 14:18发布

Excuse me if it is a repeat. I have crontab entries which look like:

*   *    *    *    *   sleep 15;/etc/opt/wer.sh
1 * * * * /opt/sfm/qwe/as.sh

How to insert a # on the line which contains a call to "as.sh" using sed?
How to uncomment it back?

3条回答
ら.Afraid
2楼-- · 2019-03-31 14:46

You can use:

sed '/\/as.sh/s/^/#/'

which will replace the start-line zero-width marker with a comment character for all lines containing /as.sh, as shown in the following example:

pax> echo '
* * * * * sleep 15;/etc/opt/wer.sh
1 * * * * /opt/sfm/qwe/as.sh
' | sed '/\/as.sh/s/^/#/'

* * * * * sleep 15;/etc/opt/wer.sh
#1 * * * * /opt/sfm/qwe/as.sh

But you need to keep in mind a couple of things.

  • It's usually not enough to just change the file, you also need to notify cron that it needs to re-read it. This is automatic if you use the crontab command itself but you may have to send a signal to cron if you're editing the file directly.
  • It's not always a good idea to turn scripts loose on important system files. Make sure you know what you're doing and don't trust any old codger on the net (including me). Test it thoroughly.

To get rid of the marker, use:

sed '/\/as.sh/s/^#//'

This is the opposite operation, it finds those lines containing /as.sh and substitute any # character at the start of the line with nothing.

查看更多
Summer. ? 凉城
3楼-- · 2019-03-31 14:48

To add the comment:

sed -e "s/\(.*\)\(as.sh\)/\#\1\2/g"

To remove the comment:

sed -e "s/\(^#\)\(.*\)\(as.sh\)/\2\3/g"
查看更多
手持菜刀,她持情操
4楼-- · 2019-03-31 14:50

use crontab -e to modify the current user's crontab.

查看更多
登录 后发表回答