wlk Asked: 2011-12-30 09:59:35 +0800 CST2011-12-30 09:59:35 +0800 CST 2011-12-30 09:59:35 +0800 CST How do I rename multiple files by removing characters in bash? 772 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. bash rename 5 Answers Voted Best Answer James O'Gorman 2011-12-30T10:14:41+08:002011-12-30T10:14:41+08:00 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. Ladadadada 2011-12-30T10:15:46+08:002011-12-30T10:15:46+08:00 Bash has some amazing scripting possibilities. Here's one way: for file in ??????*; do mv $file `echo $file | cut -c6-`; done A handy way to test what it would do is to add an echo in front of the command: for file in ??????*; do echo mv $file `echo $file | cut -c6-`; done The six question marks ensure that you only attempt to do this to filenames longer than 5 characters. wlk 2011-12-30T10:57:38+08:002011-12-30T10:57:38+08:00 All great answers, thanks. This is what worked in my case: rename 's/^.......//g' * user9517 2011-12-30T10:16:31+08:002011-12-30T10:16:31+08:00 You can use sed to do this for file in * ; do mv $file $(echo $file |sed 's/^.\{5\}//g'); done dkcm 2017-07-14T22:31:55+08:002017-07-14T22:31:55+08:00 My two cents': for file in *; do mv $file ${file:5}; done ${file:n} removes the first n characters in the string file.
A simple for loop with a bit of
sed
will do the trick:The substitute regex in
sed
says to match any five characters (.
means any character) at the start of the string (^
) and remove it.Bash has some amazing scripting possibilities. Here's one way:
A handy way to test what it would do is to add an echo in front of the command:
The six question marks ensure that you only attempt to do this to filenames longer than 5 characters.
All great answers, thanks. This is what worked in my case:
You can use sed to do this
My two cents':
${file:n}
removes the firstn
characters in the stringfile
.