繁体   English   中英

如何删除具有特定扩展名的文件的扩展名?

[英]How can I remove the extension of files with a specific extension?

我正在尝试创建一个程序,该程序将删除目录中具有该特定扩展名的文件的扩展名。

例如,存在一个目录 d1,在该目录中有三个文件 a.jpg、b.jpg 和 c.txt,我要操作的扩展名是 .jpg。

调用我的程序后,我的 output 应该是ab c.txt ,因为所有带有 .jpg 的文件现在都已从中删除了 jpg。

到目前为止,这是我尝试解决的问题:

#!/bin/bash
echo "Enter an extension"
read extension
echo "Enter a directory"
read directory
allfiles=$( ls -l $directory)
for x in $allfiles
do
        ext=$( echo $x | sed 's:.*.::')
        if [ $ext -eq $extension]
        then
                echo $( $x | cut -f 2 -d '.')
        else
                echo $x
        fi

done

但是,当我运行它时,我收到一条错误消息

'-f' is not defined
'-f' is not defined

我应该在我的代码中更改什么?

您可以通过将find的结果传递给while循环来解决您的问题:

# First step - basic idea:
# Note: requires hardening

find . -type f | while read file; do
    # do some work with ${file}
done

接下来,您可以使用${file%.*}提取不带扩展名的文件名,并使用${file##*.}提取本身的扩展名(请参阅Bash - Shell 参数扩展):

# Second step - work with file extension:
# Note: requires hardening

find . -type f | while read file; do
    [[ "${file##*.}" == "jpg" ]] && echo "${file%.*}" || echo "${file}";
done

最后一步是引入某种强化。 文件名可能包含“奇怪的”字符,如换行符或反斜杠。 我们可以强制find打印文件名后跟 null 字符(而不是换行符),然后 调整read以能够处理它

# Final step

find . -type f -print0 | while IFS= read -r -d '' file; do
    [[ "${file##*.}" == "jpg" ]] && echo "${file%.*}" || echo "${file}";
done

使用mv命令怎么样?

mv a.jpg a

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM