Trying to delete all but most recent 2 files in sub directories

坚强是说给别人听的谎言 提交于 2019-12-04 13:13:52

Unlike the existing answer, this one NUL-delimits the output from find, and is thus safe for filenames with absolutely any legal character -- a set which includes newlines:

delete_all_but_last() {
  local count=$1
  local dir=${2:-.}
  [[ $dir = -* ]] && dir=./$dir
  while IFS='' read -r -d '' entry; do
    if ((--count < 0)); then
      filename=${entry#*$'\t'}
      rm -- "$filename"
    fi
  done < <(find "$dir" \
             -mindepth 1 \
             -maxdepth 1 \
             -type f \
             -printf '%T@\t%P\0' \
           | sort -rnz)
}

# example uses:
delete_all_but_last 5
delete_all_but_last 10 /tmp

Note that it requires GNU find and GNU sort. (The existing answer also requires GNU find).

This lists all but the most recent two files:

find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -2 

Explanation:

  • -type f list only files
  • -printf '%C@ %P\n'
    • %T@ show file's last modification time in seconds since 1970.
    • %P show the file name
  • | sort -n do a numeric sort
  • | cut -d' ' -f2- drop the seconds form output, leave only the filename
  • | head -n -2 show all but the last two lines

So to remove all these files just append pipe it through xargs rm or xargs rm -f:

find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -2 | xargs rm

I just hit the same problem and that's how I solved it:

#!/bin/bash

# you need to give full path to directory in which you have subdirectories
dir=`find ~/zzz/ -mindepth 1 -maxdepth 1 -type d`

for x in $dir; do
        cd $x
        ls -t |tail -n +3 | xargs rm --
done

Explanation:

  • with tail -n +number you decide how many files you leave in subdirectories
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!