KenyKeny
KenyKeny

Reputation: 151

Batch How to remove file extension stored in string %variable%?

I got file named abcd.txt, i want to use string variable to rename the file to abcd_copy.txt. I have tried rencommand, but it just give me abcd.txt_copy.txt
My approach is to remove .txt in %variable% and then use ren abcd.txt %varialbe%"_copy.txt" to rename the file. The problematic code is shown below:

set variable=abcd.txt
ren *.txt %variable%"_copy.txt"

Any suggestions? TIA^^

Upvotes: 5

Views: 6668

Answers (3)

ripvlan
ripvlan

Reputation: 509

I suggest using the FOR loop with Parameter substitution. The FOR loop is also good if you have several files in a folder.

You want to use a combination of %~n and %~x. %~n will return the FILENAME without the extension, and %~x will return the extension.

Example:

for %i in (*.txt) do echo Filename: %~ni Extension: %~xi

Your need appears to be:

set variable=abcd.txt
for %i in (%variable%) do ren %i %~ni_copy%~xi 

which directly executes

ren abcd.txt abcd_copy.txt

Keep in mind that you need double %% when used in a batch script.

from CMD prompt try: "help for" and page down a bit. You'll see lots of options

See this link for more detail including other args... http://ss64.com/nt/syntax-args.html

You might also find something useful here - it discusses string subs. http://ss64.com/nt/syntax-replace.html

Upvotes: 2

thepirat000
thepirat000

Reputation: 13114

If you are certain that the extension are the last 4 characters (including the point), you can do:

%variable:~0,-4%

The -4 means that the last 4 digits will be truncated. So, in your case, it will be:

ren *.txt "%variable:~0,-4%_copy.txt"

Upvotes: 3

npocmaka
npocmaka

Reputation: 57252

Not tested:

set variable=abcd.txt
for %%# in ("%variable%") do ren "%%~#" "%%~n#_copy%%~x#"

Upvotes: 0

Related Questions