Riley Hun
Riley Hun

Reputation: 2785

Rename a list of files in Windows CMD

I want to add a suffix (or prefix) to each of the filenames in a specific list.

Something like the below would work, but I don't want to capture all the .tsv files in the directory, only the ones that I specify in a list

forfiles /S /M *.tsv /C "cmd /c rename @file Early_@file

The list of files would look like the below, and I would preferably want to add "Early" to the end of the filenames as a suffix, but the beginning of the filenames would work as well:

("DXOpen_BuysideAnalytics_AmerEqty_SF_20180502.tsv";"DXOpen_BuysideAnalytics_AmerEqty_IM_20180502.tsv")

Upvotes: 0

Views: 403

Answers (1)

user6811411
user6811411

Reputation:

@Echo off
Set List="DXOpen_BuysideAnalytics_AmerEqty_SF_20180502.tsv";"DXOpen_BuysideAnalytics_AmerEqty_IM_20180502.tsv"
For %%I in (%List%) Do Ren %%I "%%~nI_EARLY%%~xI"

The For command iterates through elements contained in the variable List (where elements are separated by semicolons, commas, spaces or tabs). At each iteration through the For loop, the current element is represented by the variable %%I.

The upper case letter I for a variable name is my choice, in general any letter, upper or lower case, can be used. Upper case is distinct from lower case.

The "for variable" (%I in this case) has optional modifiers. See this snippet from help for or for /?:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only

I use these modifiers to create the new name by inserting _EARLY between the original name %%~nI and the extension %%~xI

Don't get confused by the two percent signs - in a batch file they have to be doubled; on the command line use single ones.

Upvotes: 2

Related Questions