【问题标题】:Sort crontab -l in order by comment按注释排序 crontab -l
【发布时间】:2021-09-26 15:21:59
【问题描述】:

如何在每行的最后一个井号标记之后按字母顺序对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

【问题讨论】:

  • 为什么? cron 当然不在乎。除非你是强迫症,否则这看起来很愚蠢。
  • 因为我有数百个 cron 作业。我使用 python-crontab 以编程方式创建作业,使它们没有特定的顺序。按评论排序是按名称对它们进行分组,以便其他人阅读。这实际上不会对 cron 进行排序,只是对我进行版本控制的输出列表进行排序。

标签: python bash sorting cron


【解决方案1】:

使用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 代码中

【讨论】:

【解决方案2】:

使用gawk进行排序:

crontab -l | awk -F'#' '
  { comment[$NF]=$0}
  END {
    n=asorti (comment, sorted);
    for (i=1;i<=n;i++) { 
      print comment[sorted[i]]
    }
  }'

【讨论】:

  • 虽然 OP 提供的小样本不是问题,但这将过滤掉带有共同/重复评论的条目,只保留 awk 看到的“最后一个”;一个(kludge):comment[$NF,NR]=$0 ... ?
猜你喜欢
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
相关资源
最近更新 更多