当目录中有 8 个文件时,我尝试删除该目录中最旧的文件。
ls -Ct /tmp/test/ | awk '{$1=$2=$3=$4=""; print $0}' | xargs rm
我希望它删除以下输出:
ls -Ct /tmp/test/ | awk '{$1=$2=$3=$4=""; print $0}'
但我不断收到错误消息,显示这些文件不存在。我知道这是因为 xargs 正在查找我当前所在的目录,但我需要它来查看/tmp/test/。有什么办法可以做到这一点吗?
最佳答案
您编写一旦目录中有 8 个文件就删除最旧的文件。我不太确定您的意思,但我假设您留下 8 个最新文件并删除其余文件。另外,由于您标记了 awk,我正在使用 GNU awk(用于 stat()
)来完成这项工作。
首先一些测试 Material :
$ mkdir test # create test dir
$ cd test # use it
$ for i in $(seq 1 10 | shuf) ; do touch $i ;sleep 1 ; done # touch some test files
$ ls -t # 1 possible distribution
8 10 6 7 1 2 4 9 3 5
gawk 程序:
$ gawk '
@load "filefuncs" # enable stat()
BEGIN {
for(i=1;i<ARGC;i++) { # iterate argument files
ret=stat(ARGV[i],fdata) # use stat to get the mtime
mtimes[ARGV[i]]=fdata["mtime"] # hash to an array
}
PROCINFO["sorted_in"]="@val_num_desc" # set for traverse order to newest first
for(f in mtimes) # use that order
if(++c>8) # leave 8 newest
cmd=cmd OFS f # gather the list of files to rm
if(cmd) { # if any
cmd="rm -f" cmd # add rm to the beginning
print cmd # print the command to execute
# # # system(cmd) # this is the actual remove command
} # by uncommenting it you admit you
}' * # understand how the script works
# and accept all responsibility
关于bash - 一旦目录中有 8 个文件,我试图删除目录中最旧的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127566/