5

I have a directory full of files with names in this format (with numbers as the start of each filename):

102_file.txt
104_list.txt
242_another_file.txt

I would like to rename them as follows (i.e. removing the numbers):

file.txt
list.txt
another_file.txt

Can anyone suggest a way to do this (presumably from the terminal)?

Hennes
  • 65,142
Tomba
  • 395

1 Answers1

10

I assume you have the bash shell on your mac.

You can do it using the bash parameter expansion:

for name in *; do mv -v "$name" "${name#[0-9]*_}"; done

This will remove all digits up to the first _.

Note: this will overwrite files which end up having the same name.

Example:

$ ls -1
000_file0.txt
001_file1.txt
002_file1.txt
003_003_file3.txt

$ for name in ; do mv -v "$name" "${name#[0-9]_}"; done 000_file0.txt' ->file0.txt' 001_file1.txt' ->file1.txt' 002_file1.txt' ->file1.txt' 003_003_file3.txt' ->003_file3.txt'

both 001_file1.txt and 002_file1.txt will be renamed to file1.txt. in this case the file 001_file1.txt is overwriten by file 002_file1.txt. which file will get overwriten depends on the ordering of the * glob. typically it is alphanumerical.


if the separating character is some other character then replace this character

for name in *; do mv -v "$name" "${name#[0-9]*_}"; done
                                              ^ this character

for example space

for name in *; do mv -v "$name" "${name#[0-9]* }"; done
                                              ^ space
Lesmana
  • 20,163
  • This works for me where I have a space as opposed to an underscore e.g. do mv -v "$name" "${name#[0-9]* }"; done It will prompt where it needs to overwrite any files. I there a way to force this to yes for all? – Daniel Aug 03 '23 at 16:21
  • this might help you avoid prompt on overwrite https://unix.stackexchange.com/questions/83496/how-to-copy-or-move-files-without-being-asked-to-overwrite – Lesmana Aug 03 '23 at 19:47
  • Thanks. Just reading up on shell expansion. e.g. https://stackoverflow.com/questions/43771388/how-to-remove-characters-in-filename-up-to-and-including-second-underscore Apparently if you can also use an -i flag on the mv command to avoid file getting overwritten if there are any name conflicts: – Daniel Aug 04 '23 at 11:01