1

I'm looking to rename a lot of files that contain spaces in the file name while keeping the string of numbers intact. The numbers are not sequential and the string before and after the numbers are not the same for all the files. I want to make the string preceding the numbers the same for all the files.

For example:

100 foo_1.ext
200 foo_2.ext
201 foo_3.ext

renamed to

100.ext
200.ext
201.ext
  • Is it possible there would be any duplicate files after renaming? For example, two 200.ext? – Tigger Sep 6 '17 at 6:53
3

You could try:

for a in *.ext; do mv "$a" "${a/ */}.ext"; done

Explanation:

for a in *.ext - get all files with .ext extension in current directory;

a/ */ - replace substring to nothing ( ${string/substring/replacement} ). This construct get all symbols after space (inclusive) and delete it.

.

Or if you have files with different extensions and you need to processe all files in directory, try:

for a in *; do mv "$a" "${a/ *\./\.}"; done

The equivalent with the Perl rename command is:

prename 's/ .*\./\./' *

Example: files

100 foo_1.ext
200 foo_1.ext
201 foo_3.ext
3401 txt_3.txt

will renamed to

100.ext
200.ext
201.ext
3401.txt

Files without spaces in filename will not be processed.

1

Use prename for this:

prename 's/\D*(\d*).*/$1.ext/' *.ext

For all files given, this replaces the extended regular expression \D*\d*.* (a number of non-digits followed by a number of digits and the rest of the name) by the part surrounded by (), which are the digits, and the extension.

After the question was edited, it seems the filenames start with the number, followed by the space. That makes it even simpler:

prename 's/ .*/.ext/' *.ext
0

The Perl rename (not the Linux one) can be used:

prename  -n 's/(\d*)\s*foo_\d*/$1/g' /path/to/folder/*.ext

or

prename  -n 's/(\d*)\s*.*_\d*/$1/g' /path/to/folder/*.ext

Sample filenames:

100 foo_2.ext  
101 foo_1.ext   
200 foo_234.ext   
302 foo_2.ext

Results:

100.ext
101.ext
200.ext
302.ext

Info:

  1. (\d)\sfoo_\d or (\d)\s.*_\d: matches your file name
  2. (\d): returns the digits at the front
  3. $1: return value(s) variable in 2
  4. -n: used to see outcome of prename command, remove to make changes

See: man prename

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.