O'Reilly logo

bash Cookbook, 2nd Edition by JP Vossen, Carl Albing

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

Problem

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.

Solution

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
do
    mv "${FN}" "${FN%bad}bash"
done

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

Discussion

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required