Rename a group of files with one command
If I have a group of files with a .htm extention, how can I rename them all to .html?
mv *.htm *.html
does not work.
Or, you could use pure bash... (except for mv, that is..)
for file in *.htm; do mv "$file" "${file%.htm}.html"; done
and avoid the nasty basename stuff. ;)
Bash has an extensive set of variable expansion options. The one used here, '%', removes the smallest matching suffix from the value of the variable. The pattern is a glob pattern, so ${file%.*}
would also work. The '%%' operator removes the largest matching suffix, and is interchangeable in the example above, as the pattern is fixed, ${file%%.*}.html
would turn a.b.htm into a.html though.
See the variable substition section of the bash manpage for more neat tricks. There's a lot that can be done within bash directly.
There shouldn't be spaces, newlines or other whitespace in the filenames, but this version of freiheit's answer handles those. It also uses $()
instead of backticks for readability along with other benefits.
for file in *.htm
do
mv "$file" "$(basename "$file" .htm).html"
done
Even better - for the special case of just adding on to the end:
for file in *.htm
do
mv "$file" "${file}l"
done