bat file: Use of if, for and a variable all together

牧云@^-^@ 提交于 2019-12-25 05:48:12

问题


Here goes:

I want to add text to a file if it exists. The text is to go on each line of the file at the very end. The text to be added is "Note: certain conditions apply"

I found syntax to check if the file exists, and syntax for a for loop to add text at the end of the line, but they do not seem to work at the same time in the bat file.

Also, advice varies about variable names, using "%" and using the quote marks themselves, so here is what I have (assume everything takes place in the same directory)....

@echo off
setLocal EnableDelayedExpansion

PAUSE 

REM File to be modified -- 1
SET FileToModify1=abcd.txt
SET SaveFile1=abcd1.txt

PAUSE 

IF EXIST "%FileToModify1%"  (
echo Yes
)

IF EXIST "%FileToModify1%"  (
for /f "tokens=* delims= " %%a in "%FileToModify1%" do (
echo %%a   Note:  certain conditions apply  >> "%SaveFile1%"
)
)

PAUSE 

Does anyone have a suggestion on what to do here? Also, is it better to have quotes around abcd.txt or not? Why all the mysterious "%" around variables?

Please also see loop through file saving to variable for a much more efficient solution to the same problem....


回答1:


You need this (works):

for /f "tokens=* delims= " %%a in (%FileToModify1%) do (

Where you have (doesn't work, wrong syntax):

for /f "tokens=* delims= " %%a in "%FileToModify1%" do (

From the online help (via for /?)

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.

Also, is it better to have quotes around abcd.txt or not?

It's required if your file name has spaces, otherwise it's optional.Your file name doesn't have spaces so I used the simpler approach, no quotes.

Why all the mysterious "%" around variables?

Well it doesn't have to be "mysterious". Here's an example, from the command line:

> set fname=MyFile.txt
> echo %fname%

MyFile.txt

The %'s around the variable name are seen by the shell and trigger the variable expansion. To see the online help, type set /?, and you'll get more details than you can stand.



来源:https://stackoverflow.com/questions/32978156/bat-file-use-of-if-for-and-a-variable-all-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!