StrangeAttractor
StrangeAttractor

Reputation: 3

For /F in Batch: escaping type filename with spaces

I'm trying to write a utility to take a user's comma separated values file and replace single spaces and single periods with nulls:

so (spreadsheet) fields represented as , , become ,,

and fields like ,., become ,,

I'm using the type command to write the CSV to a temp file, then use string substitution on each rows before writing a new CSV with the offending values gone. !FQP! is the fully qualified path, and !INTEXTFILE! is the file name. If !INTEXTFILE! has no spaces, it works fine.

SETLOCAL ENABLEDELAYEDEXPANSION
for /f tokens^=*^ delims^=^ eol^= %%A in ('type "!FQP!!INTEXTFILE!"') do ( some commands )

However, the user's files will all have spaces in them, and I've been researching and retrying this for days trying to find a way to make this work. According to multiple pages here (For /f processing filename with spaces is the most succinct) and in other reference works, I believe I need to use "usebackq" after /f, and replace the single quotes with backticks. However, if I use it in any way (with or without quotes, after /f, before or after each of the options prior to %%A, enclosed in square brackets, written out as usebackqParsingKeywords), I get errors like these:

(when usebackq follows the /f) usebackq was unexpected at this time

(when "usebackq" follows the /f) tokens=* delims= eol= was unexpected at this time

(when "usebackq tokens^=^ delims^=^ eol^= " follows /f) tokens^=^ delims^=^ eol=" was unexpected at this time

I've tried without usebackq as well, but I know that's where the right answer lies (that's exactly what this snippet means: Specifies that you can use quotation marks to quote file names in FileNameSet, a back quoted string is executed as a command, and a single quoted string is a literal string command.)

I'll be grateful for any help with this!

I'm using Windows 7 Enterprise on a 64bit machine, so it's not a question of my using a version of Windows that doesn't support usebackq.

Upvotes: 0

Views: 955

Answers (1)

Jason Faulkner
Jason Faulkner

Reputation: 6568

Your problem is just the FOR loop is syntatically incorrect. Parameters for the FOR loop should follow the /F switch and be in quotes:

SETLOCAL EnableDelayedExpansion
FOR /F "usebackq tokens=* delims=" %%A IN (`TYPE "!FQP!!INTEXTFILE!"`) DO (
    REM Do some stuff...

    SET Value=%%A
    REM Replace spaces.
    SET Value=!Value:, ,=,,!

    REM Replace periods.
    SET Value=!Value:,.,=,,!

    ECHO !Value!
)

Upvotes: 2

Related Questions