Chapter 17. Housekeeping and Administrative Tasks

These recipes cover tasks that come up in the course of using or administering computers. They are presented here because they don’t fit well anywhere else in the book.

17.1 Renaming Many Files


You want to rename many files, but mv *.foo *.bar doesn’t work. Or, you want to rename a group of files in arbitrary ways.


We presented a simple loop to change file extensions in Recipe 5.18; see that recipe for more details. Here is a for loop example:

for FN in *.bad
    mv "${FN}" "${FN%bad}bash"

What about more arbitrary changes? For example, say you are writing a book and want the chapter filenames to follow a certain format, but the publisher has a conflicting format. You could name the files like chNN=Title=Author.odt, then use a simple for loop and cut in a command substitution to rename them:

for i in *.odt; do mv "$i" "$(echo "$i" | cut -d'=' -f1,3)"; done


You should always use quotes around file arguments in case there’s a space. While testing the code in the solution we also used echo and angle brackets to make it very clear what the arguments are (using set -x is also helpful). Once we were very sure our command worked, we removed the angle brackets and replaced echo with mv:

# Testing
$ for i in *.odt; do echo "<$i>" "<$(echo "$i" | cut -d'=' -f1,3)>"; done <ch01=Beginning Shell Scripting=JP.odt><ch01=JP.odt> <ch02=Standard Output=CA.odt><ch02=CA.odt> <ch03=Standard Input=CA.odt><ch03=CA.odt> ...

Get bash Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.