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"
done

Discussion

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 ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.