windows windows批处理文件脚本从目录中的所有文本文件中提取第三行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5522959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
windows batch file script to extract third line from all text files in a directory
提问by techdaemon
I need a a windows batch script file to extract the third line from all text files in a directory and output them on a separate text file. Can anyone help me write a batch file to extract this information? I am a rank beginner at this. Thank you!
我需要一个 Windows 批处理脚本文件来从目录中的所有文本文件中提取第三行并将它们输出到一个单独的文本文件中。谁能帮我写一个批处理文件来提取这些信息?我是这方面的初学者。谢谢!
回答by Jon
It is doable, but only with a small hack.
这是可行的,但只有一个小技巧。
First, you need to create a batch file thirdline.cmd
:
首先,您需要创建一个批处理文件thirdline.cmd
:
@echo off
for /f "skip=2 delims=" %%i in (%1) do echo %%i & goto :EOF
Then, from the command lineyou would do:
然后,从命令行您将执行以下操作:
for %i in (*.*) do @thirdline "%i"
If you want to do this from inside another batch file, you 'll need to change the %i
above to %%i
(i.e. as they appear in thirdline.cmd
).
如果您想从另一个批处理文件中执行此操作,您需要将%i
上述内容更改为%%i
(即它们出现在 中thirdline.cmd
)。
Remember to replace *.*
with the filemask that matches the files you want to process.
请记住用*.*
与您要处理的文件匹配的文件掩码替换。
Finally, thirdline.cmd
as given above just outputs the third line to the console. If you want to write it to another file (let's say lines.txt
), change thirdline.cmd
to:
最后,thirdline.cmd
如上所示,只将第三行输出到控制台。如果要将其写入另一个文件(假设lines.txt
),请更改thirdline.cmd
为:
@echo off
for /f "skip=2 delims=" %%i in (%1) do >>lines.txt echo %%i & goto :EOF
回答by Andriy M
Merely as an alternative, here's another approach:
仅作为替代方案,这是另一种方法:
SETLOCAL
(FOR /L %%i IN (1,1,3) DO SET /P line=) < filename.txt
> another.txt ECHO %line%
ENDLOCAL
Use SETLOCAL
& ENDLOCAL
whenever you can't be sure if the variables you are going to introduce with your script will not collide with the already existing ones, either defined by the system or brought along by a calling batch script, if any. Basically, use them just to be on the safe side. (Thanks Jon for the suggestion!)
每当您无法确定要通过脚本引入的变量是否与系统定义的或由调用批处理脚本带来的现有变量(如果有)发生冲突时,请使用SETLOCAL
& ENDLOCAL
。基本上,使用它们只是为了安全起见。(感谢乔恩的建议!)
回答by kurumi
If you have a choice, here's a Ruby for Windowsone liner
如果你有选择,这里有一个Ruby for Windowsone liner
$ ruby -ne "ARGF.lineno=0 if ARGF.eof?; print if ARGF.lineno==3" *.txt