For 循环和 find 命令

For 循环和 find 命令

我想仅解析 find 命令的行号。这是我的尝试:

FOR /f "tokens=1 delims=[" %a IN ('find /n "string" 2.txt') DO @ECHO %a

但它返回的是这样的:

---------- 2.TXT
2]string

而不仅仅是:

---------- 2.TXT

当我将分隔符更改为]时 - 没问题 - %a 包含:

---------- 2.TXT
[2

正如预期的那样。

答案1

FIND
Search for a text string in a file & display all the lines where it is found.

Syntax
      FIND [/V] [/C] [/N] [/I] "string" [pathname(s)]

Key
   "string"    The text string to find (must be in quotes).

   [pathname]  A drive/file(s) to search (wildcards accepted).

  ⇉  /V        Display all lines NOT containing the specified string.

     /C        Count the number of lines containing the string.

     /N        Display Line numbers.

     /I        Ignore the case of characters when searching for the string.

  [/off[line]] Do not skip files that have the offline attribute set.

1.您不需要将分隔符定义为"["或者"]"

> for /f delims^= %a IN ('find/n "string" 2.txt^|find/v "["')do @echo=%a

观察:在以下位置使用一个空格:delims^=ESPACE%a

2.只需添加^|find/v "[",省略包含[n]在输出中

> for /f delims^= %a IN ('find/n "string" 2.txt^|find/v "["')do @echo=%a
---------- 2.TXT
  • 仅获取文件名:
> for /f tokens^=1*delims^=-^  %a IN ('find/n "string" 2.txt^|find/v "["')do @echo=%a
2.TXT

观察:使用两个空格:delims^=-^ESPACEESPACE%a


其他资源:

相关内容