我正在尝试创建一个脚本,用它来删除.txt
文件的特定行。我得到了它:
@echo off
for /f "skip=1delims=*" %%a in (test.txt) do (
echo %%a >>newfile.txt
) >nul
工作正常并删除行号“1”。但是如果我删除更多行,它就不起作用,见下文:
@echo off
for /f "skip=1,5,8) delims=*" %%a in (test.txt) do (
echo %%a >>newfile.txt
) >nul
什么是worong?
答案 0 :(得分:1)
正如评论中所述,skip
没有帮助。而是添加行号(使用find /v /n ""
)并输出没有行号的原始行(token2),如果行号(token1)不在列表中:
@echo off
(for /f "tokens=1,* delims=[]" %%a in ('type test.txt^|find /v /n ""') do (
echo/%%a|findstr /x "1 5 8" >nul || echo/%%b
))>newfile.txt
(findstr
切换x
对于比较整数是很重要的,因此2018
找不到findstr "1"
||
作为“如果上一个命令(findstr
)失败,那么”
答案 1 :(得分:1)
根据建议,findstr和for /f是要使用的工具
我在失败||
或成功&&
上添加了conditional execution
如果findstr 不检测到echoed skip变量中逗号中包含的当前行号(由/ n选项生成),则Line将写入newfile。
:: Q:\Test\2018\06\09\SO_50777309.cmd
@echo off
:: generate test.txt with Line1..10
(for /l %%A in (1,1,10) do @Echo=Line%%A) >test.txt
Set "skip=,1,5,8,"
(for /f "tokens=1,*delims=:" %%a in (' findstr /n "^" ^<test.txt'
) do Echo=%skip%|findstr ",%%a," 2>&1>NUL ||Echo=%%b
)>newfile.txt
type newfile.txt
示例输出
Line2
Line3
Line4
Line6
Line7
Line9
Line10
答案 2 :(得分:0)
这是一个没有管道(|
)的变体,它应该更快。此外,应在此处正确处理带有冒号(:
)或括号([
/ ]
)的行:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "_FILE=test.txt"
set "_FNEW=newfile.txt"
set "_SKIP=,1,5,8,"
> "%_FNEW%" (
for /F "delims=" %%L in ('findstr /N "^" "%_FILE%"') do (
set "LINE=%%L"
for /F "delims=:" %%K in ("%%L") do (
setlocal EnableDelayedExpansion
if "!_SKIP!"=="!_SKIP:,%%K,=,!" (
echo(!LINE:*:=!
)
endlocal
)
)
)
endlocal
exit /B