文章目录
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.txt
pause
结果:
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 enabledelayedexpansion
setfileName=.\test.txt
setoldText=hello
setnewText=adc
setfeatureText=test
echofileName=%fileName% oldText=%oldText% newText=%newText%
if not exist %fileName% (echo txt -hello the world!>>test.txt
echo txt -hello the home!>>test.txt
echotest-hello the game!>>test.txt
)if defined featureText (echo featureText=%featureText%)
::单引号代表命令 . 表示所有内容
for /f "delims=" %%a in('findstr /n . %fileName%')do(setstr=%%a
::echo !str!
rem 替换内容
if defined featureText (
rem 查找每行字符串是否包含指定的特征字符,只对包含特征字符的行替换文本
rem >null表示不显示结果
echo!str!| findstr %featureText% >nul &&(setstr=!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
结果:
原文本内容
替换后文本内容

版权归原作者 up up day 所有, 如有侵权,请联系我们删除。