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

标签 bash awk ls xargs

当目录中有 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/

相关文章:

linux - bash 脚本。打开新终端并运行命令

windows - 从 Windows 路径 : C:\Program Files (x86)\Sublime Text 3 在 git bash 中启动 sublime text 3

linux - 使用 AWK 检查多列中的条件,以从包含年龄、种族和性别的数据集中输出平均、最小、最大和总出现次数

bash - 如何逐行连接 2 个多行字符串,就像 'paste' 对两个文件所做的那样

bash - 从另一个变量中读取多个变量

bash - 用于查找数据文件中最大和最小数字的脚本

awk - 垂直对齐尾随反斜杠

c - 在 C 中显示文件的所有者名称

Linux - 仅打印目录和子目录的文件名

linux - `ls -lh`如何舍入文件大小?