【问题标题】:testing number of files matching pattern so oldest file can be deleted if there are more than 1测试匹配模式的文件数,如果有超过 1 个,可以删除最旧的文件
【发布时间】:2023-03-04 23:51:01
【问题描述】:

我有一个包含以下文件的目录:

test_fed_1.rds
test_fed_2.rds
test_nonfed_1.rds
test_nonfed_2.rds

它们将按最后一次修改的降序排列。 我需要测试是否有多个文件与“test_fed_”匹配,以便在存在多个与给定模式匹配的文件时删除较旧的文件。

我目前有以下内容,它给出了与目录中模式匹配的文件数:

echo ${#$(find . -maxdepth 1 -name "*test_fed_*")}

给出输出2

我无法将对此的测试合并到 shell if-else 语句中,该语句查看是否有多个文件与该模式匹配,然后,如果有,则删除较旧的文件,以便只有一个与剩余模式匹配的文件(最近修改的)。

我正在寻找类似的东西:

if [[${#$(find . -maxdepth 1 -name "*test_fed_*")} > 1]]
  then ls -t inv_fed_* | tail -n 1 | xargs -d '\n' rm # <- removes last file
fi

谢谢!

【问题讨论】:

    标签: linux shell ubuntu zsh


    【解决方案1】:

    既然你标记了这个zsh,那个shell的glob qualifiers就让这变得非常简单。

    首先,将您感兴趣的文件存储在一个数组中,按正确的顺序排序,然后您可以轻松检查数组的长度并执行诸如删除最后一个元素或除第一个元素之外的所有操作之类的操作数组@ 987654322@:

    #!/usr/bin/env zsh
    
    setopt extended_glob
    
    files=( test_fed_*.rds(#qom) ) # Sort by modification time; most recent first
    
    if [[ ${#files} -gt 1 ]]; then # More than one file 
        rm "${files[-1]}" # Delete the oldest one - the last one in the array
        # rm "${files[@]:1}" # Or delete all but the newest/first file.
    fi
    

    【讨论】:

    • 做到了。谢谢!
    • @Shawn:我们真的需要#q吗?我发现只使用(om) 就可以了,不需要extended_glob
    • @user1934428 我更喜欢扩展的 glob 语法而不是裸 glob qual 形式。 (此外,它还开启了其他有用的功能。)
    猜你喜欢
    • 1970-01-01
    • 2012-07-16
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2021-11-24
    相关资源
    最近更新 更多