Windows 批处理(bat) findstr命令使用教程
文章目录
- findstr 指令基本格式
- 1. 单字符串搜索
- 2. 多字符串搜索
- 指令常用参数
- 1. 参数 /i(I) 忽略大小写
- 2. 参数 /C:string 查找包含空格的字符串所在行
- 3. 参数 /n 显示筛选结果的行号
- 4. 参数 /v 匹配结果反选
- 4. 参数 /s 递归查找
- 简单脚本应用 --文件中指定行的指定内容替换
findstr 指令基本格式
基本格式:findstr “搜索内容” 文件路径
1. 单字符串搜索
::关闭回显,设置延迟环境变量扩展
@echo off &setlocal enabledelayedexpansion:: 1.表示从test.txt中筛选包含 hello 的行,并导入到tmp.txt
findstr "hello" test.txt >>tmp.txt
:: 导入空行
echo=>>tmp.txt:: 2.表示将test.txt中所有内容导入到tmp.txt
findstr . test.txt >>tmp.txtpause
结果:

2. 多字符串搜索
@echo off &setlocal enabledelayedexpansion
findstr "hello adc" test.txt >tmp.txt
pause
指令常用参数
详细参数列表
| 参数 | 参数说明 |
|---|---|
| /B | 在一行的开始配对模式。 |
| /E | 在一行的结尾配对模式。 |
| /L | 按字使用搜索字符串。 |
| /R | 将搜索字符串作为一般表达式使用。 |
| /S | 在当前目录和所有子目录中搜索匹配文件。 |
| /I | 指定搜索不分大小写。 |
| /X | 打印完全匹配的行。 |
| /V | 只打印不包含匹配的行。 |
| /N | 在匹配的每行前打印行数。 |
| /M | 如果文件含有匹配项,只打印其文件名。 |
| /O | 在每个匹配行前打印字符偏移量。 |
| /P | 忽略有不可打印字符的文件。 |
| /OFF[LINE] | 不跳过带有脱机属性集的文件。 |
| /A:attr | 指定有十六进位数字的颜色属性。请见 “color /?” |
| /F:file | 从指定文件读文件列表 (/ 代表控制台)。 |
| /C:string | 使用指定字符串作为文字搜索字符串。 |
| /G:file | 从指定的文件获得搜索字符串。 (/ 代表控制台)。 |
| /D:dir | 查找以分号为分隔符的目录列表 |
| strings | 要查找的文字。 |
| [drive:][path]filename | 指定要查找的文件。 |
1. 参数 /i(I) 忽略大小写
@echo off &setlocal enabledelayedexpansion
findstr /i "hello" test.txt >tmp.txt
pause

2. 参数 /C:string 查找包含空格的字符串所在行
@echo off &setlocal enabledelayedexpansion
findstr /c:"t -a" test.txt >tmp.txt
pause
结果:

3. 参数 /n 显示筛选结果的行号
@echo off &setlocal enabledelayedexpansion
findstr /n "hello" test.txt >tmp.txt
pause
注意:行尾会添加一个空格
结果:

4. 参数 /v 匹配结果反选
@echo off &setlocal enabledelayedexpansion
findstr /v "hello" test.txt >tmp.txt
pause
结果:

4. 参数 /s 递归查找
@echo off &setlocal enabledelayedexpansion
:: 搜索当前目录及子目录下所有的 .txt 文件,并查找还有 hello 字符串的行, 并显示行号
findstr /n /s "hello" *.txt >tmp.txt
pause
简单脚本应用 --文件中指定行的指定内容替换
::关闭回显,设置延迟环境变量扩展
@echo off &setlocal enabledelayedexpansionset fileName=.\test.txt
set oldText=hello
set newText=adcset featureText=testecho fileName=%fileName% oldText=%oldText% newText=%newText%
if not exist %fileName% (echo txt -hello the world!>>test.txtecho txt -hello the home!>>test.txtecho test -hello the game!>>test.txt
)if defined featureText (echo featureText=%featureText%)::单引号代表命令 . 表示所有内容
for /f "delims=" %%a in ('findstr /n . %fileName%') do (set str=%%a::echo !str!rem 替换内容if defined featureText (rem 查找每行字符串是否包含指定的特征字符,只对包含特征字符的行替换文本rem >null表示不显示结果echo !str!| findstr %featureText% >nul && (set str=!str:%oldText%=%newText%!)) else (set "str=!str:%oldText%=%newText%!")rem 将添加了行号的文本写入临时文件echo !str! >>tmp.txt
)for /f "tokens=1* delims=:" %%i in (.\tmp.txt) do (rem 按 : 分割每行字符串set "str=%%j"if "!str!"==" " (rem 写入源文件里的空行echo=>>new_A.txt) else (rem 将字符串写入文本,每行会多一个空格,使用字符串的截取功能去掉末尾的一个空格echo !str:~0,-1!>>new_A.txt)
)rem 删除临时文件并将修改后的文件修改为源文件
del tmp.txt&move new_A.txt %fileName%pause
结果:
原文本内容

替换后文本内容

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
