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.
ls
– dessert Dec 14 '17 at 08:59