我想保留文件但删除其扩展名.这些文件没有相同的扩展名.我的最终目标是删除所有扩展并将其更改为我选择的一个扩展.我把第二部分放下了.
我的代码到目前为止:
#!/bin/bash
echo -n "Enter the directory: "
read path
#Remove all extensions
find $path -type f -exec mv '{}' '{}'.extension \; #add desired extension
解决方法:
您不需要为此找到外部命令,但仅在bash中执行此操作.下面的脚本从文件夹路径中的所有文件中删除扩展名.
for file in "$path"/*; do
[ -f "$file" ] || continue
mv "$file" "${file%.*}"
done
使用[-f“$file”]的原因仅用于安全检查. glob表达式“$path”/ *可能最终没有列出任何文件,在这种情况下,mv命令会因为没有文件而失败. [-f“$file”] ||当$file变量为空,其中[-f“$file”]返回失败错误代码时退出循环,继续条件保护. ||如果上一个命令失败,则在复合语句中使用时将运行,因此当下一次命中继续时,for循环终止.
如果你想添加一个新的扩展名就行了
mv "$file" "${file%.*}.extension"
标签:bash,linux,shell,sh
来源: https://codeday.me/bug/20191002/1844078.html