循环更改文件的扩展名

循环更改文件的扩展名

我想使用循环来更改一些文件的扩展名。

#!/bin/bash
read -p "type the path for folder " folder                                 
read -p "type the extention of files to be renamed " ext
read -p "type the extention you want to add " next
next=.$next
ext=.$ext
if [ $? -eq 0 ]
then
e=`ls $folder/*$ext | cut -d '.' -f1`                                      
for i in `ls $folder/*$ext`
do
mv $i $e
mv $e $e$next
done
ls $folder/*.$next
fi

我失败了。

答案1

10.1. 操作字符串-TLDP.org详细讨论 bash 字符串操作。这unix se 答案有答案的必要部分。只需将“txt”更改为$ext并将“text”更改为$next。生成的脚本可能如下所示。

#!/bin/bash
read -p "type the path for folder " folder                                 
read -p "type the extension of files to be renamed " ext
read -p "type the extension you want to add " next
# TODO add sanity checks for the user supplied input
cd $folder
# rename
#rename "s/.$ext$/.$next/" *.$ext
# mv in a loop
for f in *.$ext; do 
# the '--' marks the end of command options so that files starting with '-' wont cause problems.
# Replaces the first match for '.$ext' with '.$next'.
#mv -- "$f" "${f/$ext/$next}"
# Replaces the any match for '.$ext' with '.$next'.
#mv -- "$f" "${f//$ext/$next}"
# Replaces front-end match of for '$ext' with '$next'
#mv -- "$f" "${f/#$ext/$next}"
# Replaces back-end match of for '$ext' with '$next'
mv -- "$f" "${f/%$ext/$next}"
done

问题有许多方法不一定需要循环。我赞成rename,请参阅上述脚本中的注释行。

相关内容