cmd findstr 字符串查找增强使用说明

2019-09-19 06:51:10于丽

a.txt内容:
[code]
good hello
你好 hello world
Hello World
Hello Boy
hello ,good man.
goodbye!

如何查找以hello(忽略大小写)开始的行?
两种方法:
①./b参数
代码:

C:UsershelloworldDesktop>findstr /b /i "hello" a.txt

效果:

Hello World
Hello Boy
hello ,good man.

good hello 和 你好 hello world,这两行都没有显示出来,因为hello不在行的开始处。
②.^符
这里的^可不是转义符,而是正则表达式中的“匹配行开始的位置”。
代码:

C:UsershelloworldDesktop>findstr /i "^hello" a.txt

效果:

Hello World
Hello Boy
hello ,good man.

学完了以查找指定字符开始的行,下面学习查找以指定字符结尾的行。
如何查找以hello(忽略大小写)结尾的行?
同样有两种方法:
①./e参数
代码:

C:UsershelloworldDesktop>findstr /e /i "hello" a.txt

结果:

good hello

只显示了“good hello”,因为其它行虽然有“hello”,但是他们都没有以“hello”结尾。
②.$符
代码:

C:UsershelloworldDesktop>findstr /i "hello$" a.txt

结果:good hello
到此,我们已经学习了两个正则表达式的元字符:^和$(分别和他们功能相对应的有/b、/e参数)。
5.查找与指定字符完全匹配的行
首先修改a.txt的内容:

hello
hello hello
good hello
你好 hello world
Hello World
Hello Boy
hello ,good man.
goodbye!

懂得举一反三的的童鞋可能会试着尝试以下代码:

C:UsershelloworldDesktop>findstr /n /i "^hello$" a.txt

结果让你倍感欣喜:1:hello
其实除了这一种方法外,findstr命令还提供了/x参数用来查找完全匹配的行。
代码:

C:UsershelloworldDesktop>findstr /n /i /x "hello" a.txt

结果:

1:hello

6.关闭正则表达式会怎么样?
我们可以人为地将findstr分为两种模式,“正则表达式模式”和“普通字符串模式”。
findstr默认为“正则表达式模式”,加上/r参数也是“正则表达式模式”(换言之,/r参数有点多余)。
加上/l参数后,findstr转换为“普通字符串模式”(其实find就是这种模式、且只有这种模式)。
“普通字符串模式”下,以同样的代码,看看结果怎样?
代码:

C:UsershelloworldDesktop>findstr /li "^hello" a.txt

结果什么都没显示出来。
以hello开头的行明明有以下这些,为什么没显示出来呢?

hello hello
Hello World
Hello Boy
hello ,good man.
相关文章 大家在看