【问题标题】:Batch file that sees whatever's in the 'example.data' file and sets it as a variable查看“example.data”文件中的任何内容并将其设置为变量的批处理文件
【发布时间】:2023-03-14 18:35:02
【问题描述】:

这是一个例子: example.data 里面有“ThisIsAName”这个词。 批处理文件会看到其中写入的任何内容(因此 ThisIsAName)并执行以下命令:

set name=ThisIsAName

我该怎么做?

同样,如果 'example.data' 不存在,它会这样做:

:register
set /p name=Choose your username:
echo %name% > "example.data"
goto end

【问题讨论】:

  • 文件示例在哪里?文件中肯定还有其他行需要我们考虑吗?
  • @Gerhard 好吧,它会检查“example.data”是否存在,如果存在,则执行此操作,如果不存在,则转到 :register set /p name=Choose your username: echo %name% > "example.data" goto end 但我认为变化不大.
  • @Gerhard 'example.data' 将只有一个单词(因此在本例中为 ThisIsAName),因此它将是文件中的唯一行。
  • 您在寻找这个:set /P name="" < "example.data",还是for /F "usebackq delims=" %%I in ("example.data") do set "name=%%I"

标签: windows batch-file cmd


【解决方案1】:

一个完整的解决方案,包括您当前的代码:

@echo off
if not exist "example.data" goto :register

for /f "usebackq delims=" %%i in ("example.data") do set "name=%%i"
echo the variable is saved as %name%
goto :EOF

:register
set /p "name=Choose your username: "
(echo %name%)>"example.data"
goto end

更好的解决方案可能是不使用标签,检查文件是否存在,如果不创建它并且仍然set变量:

@echo off
if not exist "example.data" set /p "name=Choose your username: "
(echo %name%)>"example.data"

for /f "usebackq delims=" %%i in ("example.data") do set "name=%%i"
echo the variable is saved as %name%

正如用户@Stephan 强调的那样,从文件中读取(请注意此方法,因为它仅在文件只有一行时才有效:

if exist "example.data" <"example.data" set /p "name=" 
if defined name goto :welcome
set /p "name=Choose your username: "
(echo %name%)>"example.data"
:welcome
echo welcome, %name%

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 2016-09-10
    • 2011-03-05
    • 1970-01-01
    • 2019-04-19
    • 2010-09-13
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多