一旦目录中有8个文件,我试图删除目录中最旧的文件

问题描述 投票:0回答:1

一旦目录中有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 /。有什么办法可以做到?

bash awk printing ls xargs
1个回答
0
投票

您写了一旦有8个文件,便删除了目录中最早的文件。我不确定您的意思是,我假设您留下8个最新文件,然后删除其余文件。另外,由于您标记了awk,因此我正在使用GNU awk(用于stat())。首先是一些测试材料:

$ 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

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
© www.soinside.com 2019 - 2024. All rights reserved.