Changing Pieces of a String
Problem
You want to rename a number of files. The filenames are almost right, but they have the wrong suffix.
Solution
Use a bash parameter expansion feature that will remove text that matches a pattern.
#!/usr/bin/env bash
# cookbook filename: suffixer
#
# rename files that end in .bad to be .bash
for FN in *.bad
do
mv "${FN}" "${FN%bad}bash"
doneDiscussion
The for loop will iterate over a list of filenames in the current
directory that all end in .bad. The
variable $FN will take the value of
each name one at a time. Inside the loop, the mv command will
rename the file (move it from the old name to the new name). We need to
put quotes around each filename in case the filename contains embedded
spaces.
The crux of this operation is the reference to $FN that
includes an automatic deletion of the trailing bad characters. The ${ } delimit the reference so that the bash adjacent to it is just appended right on
the end of the string.
Here it is broken down into a few more steps:
NOBAD="${FN%bad}"
NEWNAME="${NOBAD}bash"
mv "${FN}" "${NEWNAME}"This way you can see the individual steps of stripping off the unwanted suffix, creating the new name, and then renaming the files. Putting it all on one line isn’t so bad though, once you get used to the special operators.
Since we are not just removing a substring from the variable but
are replacing the bad with bash, we could have used the substitution
operator for variable references, the slash (/). Similar to editor commands ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access