I am trying to truncate file names down to the last 4 digits (example: 941_S_5193 to become 5193). What would be the most straightforward way to loop this command to apply to roughly 600 files?
Thank you. -KM
The rename
command can do that well enough:
# Note, -n flag used for testing only, remove for actual renaming
$ ls
941_P_5191 941_P_5192 941_P_5193 941_P_5194
$ rename -n 's/^(.*)_([0-9]{4})$/$2/' ./*
./941_P_5191 renamed as 5191
./941_P_5192 renamed as 5192
./941_P_5193 renamed as 5193
./941_P_5194 renamed as 5194
You can also do prefix removal in bash and mv within for
loop:
$ for f in ./*; do echo mv "$f" "${f##*_}"; done
mv ./941_P_5191 5191
mv ./941_P_5192 5192
mv ./941_P_5193 5193
mv ./941_P_5194 5194
Note: remove echo
for actual renaming to take place
I would have suggested a loop through the items in the directory using
ls | tail -c 5
to list the last 4 digits of each file.
You gave 941_S_5193
as one file name, but few more would be helpful. I conjured up this find
command that did it with a sample file called 941_S_5193
:
find /users/desktop/km/neuroimage/struct/ -type f -iname '[[:digit:]]*_[[:alpha:]]_*' -exec rename -n 's/[[:digit:]]*_[[:alpha:]]_//' {} \;
Sample file names:
941_S_5194
923_D_5234
941_S_5193
941_S_5134
941_A_0034
941_C_9034
Using this command:
find /users/desktop/km/neuroimage/struct/ -type f -iname '[[:digit:]]*_[[:alpha:]]_*' -exec rename -n 's/[[:digit:]]*_[[:alpha:]]_//' {} \;
Produces these change in filenames:
rename(./941_S_5194, ./5194)
rename(./923_D_5234, ./5234)
rename(./941_S_5193, ./5193)
rename(./941_S_5134, ./5134)
rename(./941_A_0034, ./0034)
rename(./941_C_9034, ./9034)
Results:
0034
5134
5193
5194
5234
9034
Steps to fully appreciate the command are:
find /users/desktop/km/neuroimage/struct/ -type f -iname '[[:digit:]]*_[[:alpha:]]_*'
to find the files that will be changed, (1)
fails then the regex
does not match the filenames, tweak regex and update your question, elseWhen it comes up as expected now add the -exec rename -n 's/[[:digit:]]*_[[:alpha:]]_//' {} \;
part to the command in step (1), so it finds and shows you what gets renamed.
find /users/desktop/km/neuroimage/struct/ -type f -iname '[[:digit:]]*_[[:alpha:]]_*' -exec rename -n 's/[[:digit:]]*_[[:alpha:]]_//' {} \;
When done remove the -n
option to actually rename these files. Like so:
find /users/desktop/km/neuroimage/struct/ -type f -iname '[[:digit:]]*_[[:alpha:]]_*' -exec rename -n 's/[[:digit:]]*_[[:alpha:]]_//' {} \;
find /users/desktop/km/neuroimage/struct/ -type f -iname
to find the files that will be changed, then when it comes up as expected now add the -exec rename -n 's/[[:digit:]]*_[[:alpha:]]_//' {} \;
so it finds and shows you what gets renamed. When done remove the -n
option to actually rename these files.
Jun 27, 2018 at 17:14
find /users/desktop/km/neuroimage/struct/ -type f -iname '[[:digit:]]*_[[:alpha:]]_*' -exec rename 's/[[:digit:]]*_[[:alpha:]]_//' {} \;
5193
.