Quick Fixes
A sh-like prompt (eg zsh or BASH), POSIX tools and Perl are assumed. These are normally available on Unix systems or with something like Cygwin under Windows.
Rename many files
This can be done using a shell loop and some string variable handling:
for a in *.old; do mv "$a" "${a%old}new" ; done
Here ${a%old} chopped off old from the end of the variable name. You can massage the contents of environment variables in a couple of other ways:
- ${var:pos:len} returns len characters of $var from character number pos. The len argument is optional.
- ${var/patt/replace} or ${var//patt/replace} replaces patt with replace. The first version replaces the first match, the second all matches.
You can use an external command (eg sed) to parse the filenames:
for x in * do mv "$x" "$(echo $x | sed 's/patt/replace/')" done
The " quotes around variable names are necessary if the variables have special characters (including spaces) in them.
Sed one-liners
Sed (Stream EDitor) is a tool to edit streams of text, which could be files or outputs of programs. These tips are invaluable. I have mirrored them here, as the original site seems to have disappeared.
Useful Perl
Quickly replace text using a regular expression in all files in a directory:
perl -e 's/old expression/new expression/gi' -p -i *
Beware: I have had buggy versions of Cygwin Perl that have deleted my files doing this. Also a mistake in the expressions could lead to disaster. Replace -i with -i.bak to create backups of your files.
