英文:
how to comment crontab entries that match word and then restore to original
问题
我在crontab中有以下内容:
这是AAA
0 0,8 * * * ${HOME}/script.sh AAA
这是BBB
0 0,8 * * * ${HOME}/script.sh BBB
我有一个脚本,需要在开始时将BBB任务注释掉,完成后将crontab还原为原始状态。
脚本开始时需要有如下crontab:
这是AAA
0 0,8 * * * ${HOME}/script.sh AAA
这是BBB
#0 0,8 * * * ${HOME}/script.sh BBB
脚本结束后将crontab还原为以下内容:
这是AAA
0 0,8 * * * ${HOME}/script.sh AAA
这是BBB
0 0,8 * * * ${HOME}/script.sh BBB
我能够将crontab复制到一个文件,然后使用sed进行修改(有没有办法在一行中完成?)
crontab -l > crontab.bak
sed -i 's/^[^#]*BBB/#&/'' crontab.bak
然后如何去掉注释?
谢谢!
crontab -l > crontab.bak
sed -i 's/^[^#]*BBB/#&/'' crontab.bak
<details>
<summary>英文:</summary>
I have this in crontab:
this is AAA
0 0,8 * * * ${HOME}/script.sh AAA
this is BBB
0 0,8 * * * ${HOME}/script.sh BBB
I have a script that need to comment out BBB job at beginning and once finish put crontab as it was originally
at beginning of script need to have crontab like this:
this is AAA
0 0,8 * * * ${HOME}/script.sh AAA
this is BBB
#0 0,8 * * * ${HOME}/script.sh BBB
once script ends restore crontab to this:
this is AAA
0 0,8 * * * ${HOME}/script.sh AAA
this is BBB
0 0,8 * * * ${HOME}/script.sh BBB
I was able to copy crontab to a file and then modifying file with sed (any idea how to do this in one line?)
crontab -l > crontab.bak
sed -i 's/^[^#]*BBB/#&/' crontab.bak
and how to remove the comment?
thanks!
crontab -l > crontab.bak
sed -i 's/^[^#]*BBB/#&/' crontab.bak
</details>
# 答案1
**得分**: 1
使用 `sed`,如果注释存在,这将删除它(反之亦然),然后将文件加载回您的 crontab。
```bash
$ sed -E '/BBB$/{n;/^#/{s///;q};/^#/!{s/^/#/;q}};' > crontab.bak <(crontab -l) ; crontab crontab.bak
英文:
Using sed
, if the comment is present, this will remove it (and vice versa) and load the file back to your crontab.
$ sed -E '/BBB$/{n;/^#/{s///;q};/^#/!{s/^/#/;q}};' > crontab.bak <(crontab -l) ; crontab crontab.bak
答案2
得分: 0
这个答案继续自@HatLess的回答。在不使用临时文件的情况下使用单个管道:
crontab -l | sed ... | crontab -
不过,如果出现问题,你可能希望有一个备份:
crontab -l | tee crontab.bak | sed ... | crontab -
英文:
This answer follows on from @HatLess's one. Using a single pipeline without a temp file:
crontab -l | sed ... | crontab -
You might want a backup in case things go wrong though:
crontab -l | tee crontab.bak | sed ... | crontab -
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论