Renaming Files with Mathematica

I have a lot of video and text files. They all have the name: "Number-Suómething"

So for instance:

02-2.2-raKfcgvtavU.mp4

Is it possible to batch rename all the files using Mathematica to only "Number" ?

So for instance:

02.mp4

• I think it possible. Functions like FileNames, FileBaseName and NotebookDirectory might be helpful. – Αλέξανδρος Ζεγγ Oct 7 '18 at 8:56

The following method does not require a specific fixed number of digits in the start of file name and does not depend on specific fixed non-numeric separator such as "-".

rename[name_]:=
RenameFile[
name,
StringCases[name,(x:DigitCharacter..)~~___~~".mp4":>x<>".mp4"][[1]]
]


1) Back up your files, - better make a new working copy of your directory.

2) Point Wolfram Language to that directory:

SetDirectory["path to your directory"]


3) Rename files:

rename /@ FileNames[]


You can also use CopyFile instead of RenameFile in order to keep the original file and place the renamed file in a directory of your choice. Because CopyFile can copy and rename simultaneously.

• Very nice ! Thanks a lot! – james Oct 8 '18 at 5:05

Simple Just set the current working directory to the folder which contains the files:

SetDirectory["C\\…"]


And then execute this command:

RenameFile[#, StringTake[ToString[#] , 2] <> ".mp4"] & /@
FileNames["*.mp4"]


For .txt just do the same but replace the ".mp4" with ".txt"

Copy-Paste Code:

 SetDirectory["C\\…"]
RenameFile[#, StringTake[ToString[#] , 2] <> ".mp4"] & /@
FileNames["*.mp4"]
RenameFile[#, StringTake[ToString[#] , 2] <> ".txt"] & /@
FileNames["*.txt"]


You can try to map the following function over a list of full file names (with their full path). Use at your own risk.

rename = file \[Function] RenameFile[
file,
FileNameJoin[
{
DirectoryName[file],
StringSplit[FileBaseName[file], "-"][[1]] <> "." <> FileExtension[file]
}
]
]


For example, you can find all files with extension "*.mp4" in a given path path with

FileNames[FileNameJoin[{path, "*.mp4"}]]