Search code examples
pythonbashsortingcron

Sort crontab -l in order by comment


How do I sort crontab -l in alphabetical order after the last hash mark on each line?

* * * * * 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

Solution

  • Use awk to prepend each line with the last field, sort on this new 'first' field, then strip this 'first' field from the results:

    $ 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
    

    NOTES:

    • this will treat white space as a sortable character, eg, #<2_spaces>D will be sorted before #<1_space>A
    • with a bit more coding the sort|cut functionality could be rolled into the awk code