Markus Gratis Asked: 2017-01-19 21:03:40 +0800 CST2017-01-19 21:03:40 +0800 CST 2017-01-19 21:03:40 +0800 CST Remove last n characters of filenames for all files in a directory 772 How can I remove the last 12 characters of all files' filenames in a certain directory via Terminal? command-line 2 Answers Voted Best Answer heemayl 2017-01-19T21:09:17+08:002017-01-19T21:09:17+08:00 Using bash parameter expansion: for i in ?????????????*; do echo mv -i "$i" "${i%????????????}"; done remove echo for actual action. Check for same output filename for multiple source files. Also you could use parameter expansion replacement pattern: for i in ?????????????*; do echo mv -i "$i" "${i/????????????}"; done Using rename (prename), from that directory: rename -n 's/.{12}$//' * This will rename all files and directories, if you want to do for only files: find . -maxdepth 1 -type f -name '?????????????*' -exec rename -n 's/.{12}$//' {} + This will do dry-running, remove -n for actual action: find . -maxdepth 1 -type f -name '?????????????*' -exec rename 's/.{12}$//' {} + Again this could result in a race condition, make sure you check the output from the dry-running carefully. Zanna 2017-01-19T21:07:33+08:002017-01-19T21:07:33+08:00 You could use rename. From inside the directory: rename -n 's/(.*).{12}/$1/' * Remove -n after testing to actually rename the files. Replace {12} with {whatever number of characters you want to delete from the end of the name} Explanation s/old/new/' replace oldwithnew` (.*) save any number of any characters... .{12} the last twelve characters whatever they are $1 the characters saved with ()
Using
bash
parameter expansion:remove
echo
for actual action. Check for same output filename for multiple source files.Also you could use parameter expansion replacement pattern:
Using
rename
(prename
), from that directory:This will rename all files and directories, if you want to do for only files:
This will do dry-running, remove
-n
for actual action:Again this could result in a race condition, make sure you check the output from the dry-running carefully.
You could use
rename
. From inside the directory:Remove
-n
after testing to actually rename the files. Replace{12}
with{whatever number of characters you want to delete from the end of the name}
Explanation
s/old/new/' replace
oldwith
new`(.*)
save any number of any characters....{12}
the last twelve characters whatever they are$1
the characters saved with()