Escaping special characters batch for loop

I have a loop that iterates on a text file where I have several file paths on each line.

The goal is to iterate throw file paths and copy them to a different location.

I’m not a windows beast (pref UNIX) but managed to make it works:

@echo off
For /f "tokens=* delims=" %%a in ('type file_list.txt') do xcopy /hrkvy "%%a" "S:\dest_dir"

The paths in the .txt are full path pointing to some files. There is one path every line. The final result is a script that should copy files stored elsewhere on the computer right to the location I launched the script.

The issue is that some paths contain characters like single quotes which make my code to not work. Here is an example of the file_list.txt:

C:\temp\path with single quote ' - 1.txt   // doesn't work
C:\temp\path without single quote - 2.txt  // work
C:\temp\path with single quote ' - 3.txt   // doesn't work

However it doesn’t work for paths that contain special characters. It's possible that some characters other than single quote are causing issues to. I have no idea how to scape those characters from a loop. Any idea?

Upvotes: 0

Views: 872

Answers (1)

jeb
jeb

Reputation: 82287

Your problem description is missing too many information.
Without showing a sample file or explain which special characters, do you think, are problematic, it's hard to guess what the real problem is.

But the only problematic special characters in such a case, when using "%%a", a quoted for meta variable, are the exclamation mark ! and the caret ^, but only when you have delayed expansion enabled!
You can get more problems, if your paths are surrounded by quotes itself.

But modifying it a bit, should solve any problems.

@echo off
setlocal DisableDelayedExpansion
For /f "delims=" %%a in (file_list.txt) do (
  xcopy /hrkvy "%%~a" "S:\dest_dir"
)

Upvotes: 0

Related Questions