Bash – How to rename multiple files by removing characters in bash

bashrename

I have to rename multiple files in directory by removing first 5 characters for each filename.
How can I do this i bash/shell? I'm using Ubuntu 11.10. Thanks.

Best Answer

A simple for loop with a bit of sed will do the trick:

% touch xxxxx{foo,bar,baz}
% ls -l xxxxx{foo,bar,baz}
-rw-r--r--  1 jamesog  wheel  0 29 Dec 18:07 xxxxxbar
-rw-r--r--  1 jamesog  wheel  0 29 Dec 18:07 xxxxxbaz
-rw-r--r--  1 jamesog  wheel  0 29 Dec 18:07 xxxxxfoo  
% for file in xxxxx*; do mv $file $(echo $file | sed -e 's/^.....//'); done
% ls -l foo bar baz
-rw-r--r--  1 jamesog  wheel  0 29 Dec 18:07 bar
-rw-r--r--  1 jamesog  wheel  0 29 Dec 18:07 baz
-rw-r--r--  1 jamesog  wheel  0 29 Dec 18:07 foo

The substitute regex in sed says to match any five characters (. means any character) at the start of the string (^) and remove it.