0

I want to change extentions of a few files, using loop.

#!/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

I'm failing.

muru
  • 197,895
  • 55
  • 485
  • 740
Josef Klimuk
  • 1,596

1 Answers1

2

See 10.1. Manipulating Strings-TLDP.org for a thorough discussion of bash string manipulation. This unix se answer has the essential part of the answer. Just change "txt" to $ext and "text" to $next. The resulting script could look like.

#!/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

This question has many approaches that don't necessarily need a loop. I would favor rename, see the commented lines in the above script.

J. Starnes
  • 1,969