【问题标题】:Bat file to create & write to a fileBat文件创建和写入文件
【发布时间】:2014-10-26 01:34:51
【问题描述】:

我正在尝试使用 .bat 创建和写入文件

@echo off

echo Jackdows loves my big sphinx >> %appdata%\data.html
echo Of quartz. >> %appdata%\data.html

exit

正常工作。但是,如果用户再次运行它,它会再次将相同的值写入文件。所以在文件中,有多个值。有没有可能防止这种情况发生?

【问题讨论】:

  • 将第一个重定向更改为单个> chevron 以清除文件的现有值。否则,如果您想保留文件的内容,则需要使用find 命令检查您的行是否已存在于文件中。

标签: batch-file command-line cmd


【解决方案1】:

>> 将文本附加到文件中,无论它是否存在于文件中的其他位置。但是,您可以先在文件中搜索该字符串,然后仅在该行不存在时追加该行。

@echo off

:: Appends a string to a file only if that string is not present in that file
call :ainp "Jackdaws love my big sphinx" text.txt
call :ainp "Of quartz" text.txt
call :ainp "Rule Brittania" text.txt

exit /b

:: Append If Not Present
:AINP
set "search_string=%~1"
set "search_file=%~2"

>nul find "%search_string%" %search_file%
if %errorlevel% equ 1 (
    >>%search_file% echo %search_string%
)

【讨论】:

  • 只写第一行
  • 我刚刚运行了它。它在您运行脚本的同一路径中创建文件。
  • 另外,如果其他行已经在文件中的任何其他位置,则不会添加它们。检查文件并查看这些行是否存在。
猜你喜欢
  • 1970-01-01
  • 2011-12-11
  • 2014-10-07
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 2010-10-09
  • 2023-04-03
  • 2022-01-25
相关资源
最近更新 更多