Batch : read lines from a file having spaces in its path

后端 未结 3 654
逝去的感伤
逝去的感伤 2021-01-12 11:15

To read lines from a file, in a batch file, you do :

for /f %%a in (myfile.txt) do (
    :: do stuff...
)

Now suppose you file is in

相关标签:
3条回答
  • 2021-01-12 11:52

    Found it.

    for /f %%a in ('type "C:\Program Files\myfolder\myfile.txt"') do (
        echo Deleting: %%a
    )
    

    Don't even ask me why that works.

    0 讨论(0)
  • 2021-01-12 11:58

    The documentation you get when you type help for tells you what to do if you have a path with spaces.

    For file names that contain spaces, you need to quote the filenames with
    double quotes.  In order to use double quotes in this manner, you also
    need to use the usebackq option, otherwise the double quotes will be
    interpreted as defining a literal string to parse.
    

    By default, the syntax of FOR /F is the following.

    FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
    FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
    FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
    

    This syntax shows why your type workaround works. Because the single quotes say to execute the type command and loop over its output. When you add the usebackq option, the syntax changes to this:

    FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
    FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
    FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
    

    Now you double quote paths to files, single-quote literal strings, and put backticks (grave accents) around commands to execute.

    So you want to do this:

    for /f "usebackq" %%a in ("C:\Program Files\myfolder\myfile.txt") do (
        echo %%a
    )
    
    0 讨论(0)
  • 2021-01-12 12:08

    Just sharing the below code, hoping that somebody will get benefited.

    The below code take both the path having spaces and also if the read lines has spaces, it wont cause any issue of the characters after space is missing;

    FOR /f "tokens=* delims=," %%a in ('type "C:\Progrem File\My Program"') do ( echo %%a )

    0 讨论(0)
提交回复
热议问题