打印行如果包含单词

时间:2015-03-05 15:10:02

标签: batch-file

我正在尝试制作一个批处理文件来为我执行一些操作。
现在我理解了一些编程语言,但我还没有在批处理文件编程方面做过多少工作。

我开始很简单。 我需要一个批处理文件来读取文件并逐行读取。
如果该行包含单词“node”,我想在命令提示符下打印该行。

file1 =我读过的文件是由用户提供的。
那部分有效。

for /f "tokens=*" %%l in (%file1%) do (
    REM Find the lines that contain: node
    if exist "node" in %%l (
        echo %%l
    )
    REM for %%i in ('findstr "node" %%l') do (
        REM echo %%l
    REM )
)

我评论过的部分我也试过了。
但是它们都不起作用。
它一直都会返回所有行。

任何人都可以给我一个关于我做错的提示吗?

2 个答案:

答案 0 :(得分:3)

如果您只想输出没有逻辑检查的匹配行,请执行

findstr /i "node" "%file1%"

如果要在找到该行时执行某些代码,请使用conditional execution

findstr /i "node" "%file1%" && (

    rem File contained "node".  Do some stuff.

) || (

    rem File did not contain "node".  Do something else.

)

如果您想使用findstr来测试字符串的存在而不将结果实际转储到控制台,只需在>NUL命令之前或之后添加findstr即可。

>NUL findstr /i "node" "%file1%" && (success) || fail

答案 1 :(得分:2)

如果您不熟悉脚本,我会避免批处理(shell脚本)并使用PowerShell。 PowerShell功能更强大,更灵活。

get-content 'file.txt' | select-string 'node:(\s+)' | foreach-object {
  $_.Matches[0].Groups[1].Value
}

此命令将从每一行输出第一个子字符串匹配(来自正则表达式中的括号内)。

相关问题