【问题标题】:Find and replace line starts with specific value in text file via windows batch file通过Windows批处理文件查找和替换行以文本文件中的特定值开头
【发布时间】:2016-04-26 08:29:56
【问题描述】:

即使经过深入的谷歌搜索,我也无法解决我的问题。 有一个名为 test.txt 的文本文件。我需要的是更改以单词“Root:”开头的行以及其他内容 - 使用批处理文件。

setLocal EnableDelayedExpansion    
FINDSTR /B Root: test.txt 
::returns the correct line - works well
for /f %%i in ('FINDSTR /B Root: test.txt') do set root=%%i

echo %root%
::echos "Root:" - instead of the line content

FOR /F "tokens=*" %%G IN (test.txt) DO 
(set x=%%G
if !x!==%root% set x=Hello
echo !x! >> test.txt)
::The syntax of the command is incorrect.

我该怎么做?

编辑: 基于 Magoo 和 Batch / Find And Edit Lines in TXT file 的 RobW - 我的问题解决如下:

for /f "tokens=*" %%i in ('"FINDSTR /B Root: test.txt"') do set root=%%i
::root holds test.txt's line starts with "Root:"
echo %root%

SETLOCAL=ENABLEDELAYEDEXPANSION
::iterate on test.txt's lines and compare to the root's value
        rename test.txt test.tmp
        for /f "tokens=*" %%a in (test.tmp) do (
            set foo=%%a
            echo !foo!
            echo %root%
            echo "%root%"
            if "!foo!"=="%root%" (set foo=hello)
            echo !foo! >> test.txt)                                       
    del test.tmp

谢谢! 罗尼

【问题讨论】:

  • 语法错误是因为 ( 必须与 DO 在同一行。
  • 在您的第一个for /F 循环中,您需要提供选项"delims=" 以获取整行;否则,delims 默认为 tabspace,因此只返回第一个标记...

标签: batch-file text replace


【解决方案1】:
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q34900978.txt"

FINDSTR /B Root: "%filename1%" 
::returns the correct line - works well
FOR /f "tokens=*" %%i IN (
 'FINDSTR /B Root: "%filename1%"
') do set "root=%%i"

echo %root%
::echos "Root:" - instead of the line content

FOR /F "usebackqdelims=" %%G IN ("%filename1%") DO (
 if "%%G"=="%root%" (
  ECHO(x=Hello
 ) ELSE (
 ECHO(%%G
 )
)

GOTO :EOF

您需要更改sourcedir 的设置以适应您的情况。

我使用了一个名为 q34900978.txt 的文件,其中包含一些用于我的测试的虚拟数据。

for...%%i(或delims=)中的tokens=* 选项将整行分配给“token 1”,然后分配给元变量%%i

默认分配token 1,但使用 [SpaceTab,;] 作为分隔符,因此,您的代码只得到字符串Root:(最多但不包括默认分隔符)

对于 /?

从文档提示中。

语法SET "var=value"(其中值可能为空)用于确保分配的值中不包含任何杂散的尾随空格。 set /a 可以安全地“无引号”使用。

下一步是处理文件。同样的故事(但由于我引用文件名并提供完整路径,我需要 usebackq 选项。

整行分配给%%G(注意:除了空行和以开头的行;

那么这是一个简单的if 语句 - if "the line content"=="target content"。引号是必需的,因为引号将“包含分隔符的字符串”分组为一个字符串,if 语法为 if string operator string2 (dothis) else (dothat)`

请注意,左括号必须与 do 位于同一物理行,if 也是如此。 else,前面的右括号和后面的左括号必须都在同一物理线上,并且它们之间有一个空格。

注意ECHO( 的使用,如果%%G(在这种情况下)没有值,则echo 将是一个空行。就嵌套而言,( 不算在内。

(这里的%%G 必须有一个值——但在一般情况下,如果var 未定义,echo %var% 将产生echo is on/off,但echo(%var% 将干净地产生一个新行)

【讨论】:

猜你喜欢
  • 2019-03-13
  • 2012-07-22
  • 1970-01-01
  • 2021-06-29
  • 2021-07-05
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
相关资源
最近更新 更多