Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add character to the middle of a file name

I need to add a character to the middle of a file name, I need to do this for about 8000 files all in the same directory. I'm looking for a command-line option:

Example (all files that need renaming are five digits, they are in a directory that contains other six-digit filenames that do not need to be renamed):

01011
02022
12193

To:

010101
020202
121903

I've tried a couple of things: rename, mv, etc. Similar to this (Bash - Adding 0's in the middle of a file name) but not exactly

like image 579
steve-er-rino Avatar asked Aug 10 '13 03:08

steve-er-rino


People also ask

How do you cat a file with a space in the name?

Another way to deal with spaces and special characters in a file name is to escape the characters. You put a backslash ( \ ) in front of the special character or space.

How do you handle spaces in filename?

Use quotation marks when specifying long filenames or paths with spaces. For example, typing the copy c:\my file name d:\my new file name command at the command prompt results in the following error message: The system cannot find the file specified. The quotation marks must be used.

Which characters are allowed in file names?

Supported characters for a file name are letters, numbers, spaces, and ( ) _ - , . *Please note file names should be limited to 100 characters. Characters that are NOT supported include, but are not limited to: @ $ % & \ / : * ?


2 Answers

You can write:

for file in * ; do
    mv ./"$file" "${file:0:4}0${file:4}"
done

(See the explanation of ${parameter:offset} and ${parameter:offset:length} in §3.5.3 "Shell Parameter Expansion" of the Bash Reference Manual.)

Edited to add: If you only want to capture a specific subset of files, you can change * to a more-specific pattern such as [0-9][0-9][0-9][0-9][0-9] (which matches filenames consisting of five digits).

Incidentally, you can format the whole thing on one line:

for file in [0-9][0-9][0-9][0-9][0-9] ; do mv "$file" "${file:0:4}0${file:4}" ; done
like image 110
ruakh Avatar answered Sep 25 '22 15:09

ruakh


Try using below code.

rename -v -n "s/(S01S0[0-2][0-9])/\$1-/" *

-n to check the command output.

like image 43
edu Avatar answered Sep 26 '22 15:09

edu