Wednesday, May 27, 2009

How to Change File Extensions

Changing file extensions is easier than people make it out to be. Even on sites that provide shell programming tips, I see recipes like this:
#!/bin/sh

for file in *.dat ;

do mv $file `echo $file | sed 's/\(.*\.\)dat/\1txt/'` ;

done
It's easier than that. Honest.
$ for file in *.dat; do mv $file ${file/.dat/.txt}; done
All in the same, parent shell. One process. No pipes, no sed, no magic regex metacharacters. So easy, you can type it on the command line.

I do it all the time.

If I need to be careful, I start like this:
      $ for file in *.dat; do echo mv $file ${file/.dat/.txt}; done
Then, if the output commands look like what I intended, I recall the loop, and tack a pipe of its output to bash on the end, like this:
      $ for file in *.dat; do echo mv $file ${file/.dat/.txt}; done | bash

No comments: