【问题标题】:Remove files with unique basename?删除具有唯一基本名称的文件?
【发布时间】:2015-10-31 23:44:54
【问题描述】:

我有一个文件夹包含类似的文件

a.JPG
a.GIF
b.JPG
c.JPG
c.GIF
d.GIF

b.JPGd.GIF 文件在其文件名的基本名称部分仅出现一次,所以我想删除 b.JPGd.GIF,如何在 bash 中做到这一点?

【问题讨论】:

    标签: linux bash shell command


    【解决方案1】:

    这是一个合理的程序:

    1.- 不带引号的 * 将列出所有文件:循环遍历它们。

    2.- 可以使用${myfile%.*} 删除尾随扩展

    3.- 使用星号扩展名称 name.*(点以确保名称结束)。

    4.- 并将结果捕获到一个数组中:“tocount=( ... )”

    5.- 最后,如果数组计数为 1,则删除文件。

    还有代码:

    for myfile in *; do
        tocount=( "${myfile%.*}".* )
        [[ ${#tocount[@]} -eq 1 ]] && rm "$myfile"
    done
    

    【讨论】:

    • @glennjackman 感谢您的编辑。我添加了一个有用的点以避免"c d.GIF""c.GIF" 之类的文件被"${myfile%.*}"* 的扩展捕获。
    【解决方案2】:

    在 bash 版本 4 中使用关联数组

    declare -A count
    # count each root-name
    for f in *; do
        (( count["${f%.*}"] ++ ))
    done
    # delete the files with count 1
    for key in "${!count[@]}"; do
        if (( ${count["$key"]} == 1 )); then
            rm "$key"*
        fi
    done
    

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      相关资源
      最近更新 更多