首页 > 解决方案 > 按注释排序 crontab -l

问题描述

如何crontab -l在每行的最后一个哈希标记之后按字母顺序排序?

* * * * * curl -m 10 https://google.com # C comment
# * * * * * curl -m 10 https://google.com # A comment
* * * * * curl -m 10 https://google.com # D comment
* * * * * curl -m 10 https://google.com # E comment
* * * * * curl -m 10 https://google.com # Z comment
## * * * * * curl -m 10 https://google.com # B comment

标签: pythonbashsortingcron

解决方案


用于awk在每一行前面加上最后一个字段,对这个新的“第一个”字段进行排序,然后从结果中删除这个“第一个”字段:

$ crontab -l | awk -F'#' '{print $NF"#"$0}' | sort -t'#' -k1,1 | cut -d'#' -f2-
# * * * * * curl -m 10 https://google.com # A comment
## * * * * * curl -m 10 https://google.com # B comment
* * * * * curl -m 10 https://google.com # C comment
* * * * * curl -m 10 https://google.com # D comment
* * * * * curl -m 10 https://google.com # E comment
* * * * * curl -m 10 https://google.com # Z comment

笔记:

  • 这会将空白视为可排序字符,例如,#<2_spaces>D将在之前排序#<1_space>A
  • 通过更多的编码,sort|cut可以将功能整合到awk代码中

推荐阅读