简体   繁体   中英

Issue while reading the text from file using batch file

I'm trying to write one batch file which will read text from a text file and set to a variable.

This is the text file.

out.txt

C:\Program Files (x86)\Windows NT\text1.txt
C:\Program Files (x86)\Windows NT\text2.txt
C:\Program Files (x86)\Windows NT\text3.txt
   3 file(s) copied. 

Here my doubt is I want to set C:\\Program Files (x86)\\Windows NT to a variable. I tried with the following command which will hold the complete text file.

FOR /f "delims=/" %%a IN (out.txt) DO echo %%a

Can anyone please tell me how can I read a particular string from the text file.

Thanks In Advance.

If I understand correctly, you want to get the full path of the files mentioned in out.txt , but without the filename. This can be done using parameter extensions , like this:

FOR /f "delims=" %%a IN (out.txt) DO ECHO %%~dpa

In your example, it will output

C:\Program Files (x86)\Windows NT\
C:\Program Files (x86)\Windows NT\
C:\Program Files (x86)\Windows NT\

Update: To save only the result of the first line , use this:

@ECHO OFF
FOR /f "delims=" %%a IN (out.txt) DO (
    SET path_in_first_line=%%~dpa
    GOTO skip
)
:skip
ECHO %path_in_first_line%

Splitting the line using the backslash as a delimiter

for /f "tokens=1-3 delims=\" %%a in (out.txt) do set "var=%%a\%%b\%%c"
echo %var%

Asking for the drive and path of the element in the line

for /f "delims=" %%a in (out.txt) do set "var=%%~dpa"
echo %var%

Of course, as the for command iterates over all the lines in the file, the var variable will only hold the value retrieved from the last line in the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM