How to Rename Multiple Files With Their First 10 Characters?
12,321
Solution 1
You can try:
rename -n 's/(.{10}).*(\.jpg)$/$1$2/' *.jpg
Example:
$ rename -n 's/(.{10}).*(\.jpg)$/$1$2/' *.jpg
11512345714x611aaa.jpg -> 1151234571.jpg
1201230111FbcAdee.jpg -> 1201230111.jpg
1208605001abAcd.jpg -> 1208605001.jpg
The -n
option only simulates the command, so that you can verify the changes. Run without it to actually make the changes.
The regex (.{10}).*(\.jpg)
consists:
.{10}
- any 10 characters, in a group(…)
, followed by.*
- any number of any characters followed by\.jpg$
- the extension at the end ($
) of the filename, in the second group
The replacement $1$2
is just the first group followed by the second.
Solution 2
You can do with only bash:
for FILE in *.jpg ; do mv "${FILE}" "${FILE:0:10}.jpg" ; done
With a little work you can get file extension and add automagically to the new name.
Solution 3
If you use zsh
:
zmv '(*).(*)' '${1:0:10}.$2'
If it's not already done, you may need to first run:
autoload zmv
Related videos on Youtube
Author by
surya_darmana
Updated on September 18, 2022Comments
-
surya_darmana almost 2 years
I am having a problem to rename multiple files by replacing the name by their first 10 characters of their old name. I tried to find the solution in internet but I didn't find the answers.
Example:
Original File Names:
1208605001abAcd.jpg 1201230111FbcAdee.jpg 11512345714x611aaa.jpg
What I want to achieve:
1208605001.jpg 1201230111.jpg 1151234571.jpg
-
surya_darmana about 8 yearsSorry if I am missing something, when I tried to run your suggested command I've got this message : "Substitution replacement not terminated at (eval 1) line 1.". Did I do something wrong?
-
muru about 8 years@surya_darmana there was supposed to be a
/
after$2
. The example output has it correct. I have fixed it. -
surya_darmana about 8 yearsThank you very much, the command is run perfectly, you made my day :D
-
Kevin about 8 yearsUse globbing (
*
) instead ofls
(for which you wouldn't need the-1
anyway), and quote the variables. ("${FILE:0:10}.jpg"
). -
muru about 8 yearsWill this keep the extensions?
-
Kevin about 8 years@muru no, I didn't notice that particular requirement. Updated with a version that does.
-
Reinier Post about 8 yearsThis holds for the
rename
that comes withperl
(e.g. on Ubuntu), not the one that comes withutil-linux
(e.g. on Fedora, CentOS, Cygwin). -
Antonio about 8 yearsI prefer using ls, but +1 for the quoting! (error of distraction).
-
Kevin about 8 yearsIt isn't a matter of preference, using
ls
will break on files with spaces in the name. Globbing won't.