使用bash,如何删除特定目录中所有文件的扩展名? [英] Using bash, how can I remove the extensions of all files in a specific directory?

查看:53
本文介绍了使用bash,如何删除特定目录中所有文件的扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保留文件,但删除其扩展名.这些文件的扩展名不同.我的最终目标是删除所有扩展名并将其更改为我选择的一个扩展名.我有第二部分.

I want to keep the files but remove their extensions. The files do not have the same extension to them. My end goal is to remove all their extensions and change them to one single extension of my choice. I have the second part down.

到目前为止,我的代码:

My code so far:

#!/bin/bash
echo -n "Enter the directory: "
read path
            #Remove all extensions
find $path -type f -exec mv '{}' '{}'.extension \; #add desired extension

推荐答案

为此,您不需要外部命令 find ,而只需在 bash 中执行即可.下面的脚本从文件夹 path 中的所有文件中删除扩展名.

You don't need an external command find for this, but do it in bash alone. The script below removes the extension from all the files in the folder path.

for file in "$path"/*; do
    [ -f "$file" ] || continue
    mv "$file" "${file%.*}"
done

使用 [-f"$ file"] 的原因仅出于安全检查.全局表达式"$ path"/*可能最终没有列出任何文件,在这种情况下,由于没有文件, mv 命令将失败. [-f"$ file"] ||当 $ file 变量为空(其中 [-f"$ file"] 返回失败错误代码)时,continue 条件通过退出循环来保护这一点.如果上一条命令失败,则在复合语句中使用 ||| 时,它将运行,因此,当下次单击 continue 时,for循环将终止.

The reason for using [ -f "$file" ] is only for a safety check. The glob expression "$path"/* might end up in no files listed, in that case the mv command would fail as there are no files. The [ -f "$file" ] || continue condition safeguards this by exiting the loop when the $file variable is empty in which the [ -f "$file" ] returns a failure error code. The || when used in a compound statement will run if the previous command fails, so when continue is hit next, the for loop is terminated.

如果您要添加新的扩展名,只需

If you want to add a new extension just do

mv "$file" "${file%.*}.extension"

这篇关于使用bash,如何删除特定目录中所有文件的扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆