Windows批处理命令从文本文件读取第一行
时间:2020-03-06 14:41:26 来源:igfitidea点击:
如何使用Windows批处理文件从文本文件中读取第一行?由于文件很大,所以我只想处理第一行。
解决方案
我们可以尝试一下:
@echo off for /f %%a in (sample.txt) do ( echo %%a exit /b )
编辑
或者,假设我们有四列数据,并且想要从第五行向下到底部,请尝试以下操作:
@echo off for /f "skip=4 tokens=1-4" %%a in (junkl.txt) do ( echo %%a %%b %%c %%d )
多亏了talkingwalnut可以回答Windows批处理命令,以便从文本文件中读取第一行,所以我提出了以下解决方案:
@echo off for /f "delims=" %%a in ('type sample.txt') do ( echo %%a exit /b )
稍微建立在其他人的答案上。现在,我们可以指定要读取的文件以及要将结果放入其中的变量:
@echo off for /f "delims=" %%x in (%2) do ( set %1=%%x exit /b )
这意味着我们可以像这样使用上面的代码(假设我们将其命名为getline.bat)
c:\> dir > test-file c:\> getline variable test-file c:\> set variable variable= Volume in drive C has no label.
这是一个通用批处理文件,用于从GNUhead
实用程序之类的文件中打印前n行,而不是仅打印一行。
@echo off if [%1] == [] goto usage if [%2] == [] goto usage call :print_head %1 %2 goto :eof REM REM print_head REM Prints the first non-blank %1 lines in the file %2. REM :print_head setlocal EnableDelayedExpansion set /a counter=0 for /f ^"usebackq^ eol^=^ ^ delims^=^" %%a in (%2) do ( if "!counter!"=="%1" goto :eof echo %%a set /a counter+=1 ) goto :eof :usage echo Usage: head.bat COUNT FILENAME
例如:
Z:\>head 1 "test file.c" ; this is line 1 Z:\>head 3 "test file.c" ; this is line 1 this is line 2 line 3 right here
当前不计算空白行。它也受批处理文件行长度限制为8 KB。
一根衬线,可用于使用">"重定向stdout:
@for /f %%i in ('type yourfile.txt') do @echo %%i & exit
注意,批处理文件的方法将限于DOS命令处理器的行数限制,请参阅什么是命令行长度限制?
因此,如果尝试处理任何行多于8192个字符的文件,脚本将跳过它们,因为无法保留该值。