Linux - Save only recent 10 folders and delete the rest

后端 未结 6 1730
借酒劲吻你
借酒劲吻你 2021-02-04 14:14

I have a folder that contains versions of my application, each time I upload a new version a new sub-folder is created for it, the sub-folder name is the current timestamp, here

相关标签:
6条回答
  • ls -dt1 /path/to/folder/*/ | sed '11,$p' | rm -r 
    

    this assumes those are the only directories and no others are present in the working directory.

    • ls -dt1 will normally only print the newest directory however the /*/ will only match directories and print their full paths the 1 ensures one line per match/listing t sorts time with newest at the top.

    • sed takes the 11th line on down to the bottom and prints only those lines, which are then passed to rm.

    You can use xargs, but for testing you may wish to remove | rm -r to see if the directories are listed properly first.

    0 讨论(0)
  • 2021-02-04 14:40

    Your directory names are sorted in chronological order, which makes this easy. The list of directories in chronological order is just *, or [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] to be more precise. So you want to delete all but the last 10 of them.

    set [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/
    while [ $# -gt 10 ]; do
      rm -rf "$1"
      shift
    fi
    

    (While there are more than 10 directories left, delete the oldest one.)

    0 讨论(0)
  • 2021-02-04 14:48
    ls -lt | grep ^d | sed -e '1,10d' |  awk '{sub(/.* /, ""); print }' | xargs rm -rf 
    

    Explanation:

    • list all contents of current directory in chronological order (most recent files first)
    • filter out all the directories
    • ignore the 10 first lines / directories
    • use awk to extract the file names from the remaining 'ls -l' output

    • remove the files

    0 讨论(0)
  • 2021-02-04 14:58

    EDIT:

    find . -maxdepth 1 -type d ! -name \\.| sort | tac | sed -e '1,10d' | xargs rm -rf
    
    0 讨论(0)
  • 2021-02-04 15:03

    There you go. (edited)

    ls -dt */ | tail -n +11 | xargs rm -rf

    First list directories recently modified then take all of them except first 10, then send them to rm -rf.

    0 讨论(0)
  • 2021-02-04 15:03

    If the directories' names contain the date one can delete all but the last 10 directories with the default alphabetical sort

    ls -d */ | head -n -10  | xargs rm -rf
    
    0 讨论(0)
提交回复
热议问题