crontab -l 按注释排序

Sort crontab -l in order by comment

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

使用 awk 在每一行前加上最后一个字段,在这个新的 'first' 字段上排序,然后从结果中删除这个 'first' 字段:

$ crontab -l | awk -F'#' '{print $NF"#"[=10=]}' | 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

备注:

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

使用gawk排序:

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