Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a batch file to handle spaces in file names?

I am using the following batch file to make a zip file for each xml in a folder:

FOR %%f in ("C:\files\*.xml") DO 7za.exe a C:\files\zips\%%~nf.zip (%%f)

However if the file name has a space in it (test plop.xml) then the batch file does not work. It seems to split the name and thinks it is 2 files.

How to modify the batch file so that it properly handles file names with spaces?

like image 849
john Avatar asked Jan 26 '11 14:01

john


People also ask

How do you handle spaces in a batch file?

When you send arguments, those with poison or space characters need to be doublequoted. Inside your batch file, if you no longer need the surrounding doublequotes, you'd remove them by using %~5 instead of %5 . Additionally the recommended syntax for the set command is Set "VariableName=VariableValue" .

How do you handle spaces in file names?

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.

How do you handle spaces in CMD?

In the Command Prompt, the caret character ( ^ ) will let you escape spaces—in theory. Just add it before each space in the file name. (You'll find this character in the number row on your keyboard.

What does %% do in batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

Can a filename include spaces?

Don't start or end your filename with a space, period, hyphen, or underline. Keep your filenames to a reasonable length and be sure they are under 31 characters. Most operating systems are case sensitive; always use lowercase. Avoid using spaces and underscores; use a hyphen instead.

What is %% g'in batch file?

%%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G) FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'.


1 Answers

Try placing quotes around the output file name.

Change

FOR %%f in ("C:\files*.xml") DO 7za.exe a C:\files\zips\%%~nf.zip (%%f)

to:

FOR %%f in ("C:\files*.xml") DO 7za.exe a "C:\files\zips\%%~nf.zip" (%%f)

May also be the variable %%f, may need to place quotes around this as well.

like image 152
Fred Avatar answered Nov 16 '22 00:11

Fred