На этот вопрос уже есть ответ здесь:
Я хочу изменить расширения нескольких файлов с помощью цикла.
#!/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
Я терплю поражение.
См. 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
, см. Закомментированные строки в приведенном выше сценарии.