如何使用Windows批处理文件从文本文件中读取第一行?由于文件很大,我只想处理第一行。
如何使用Windows批处理文件从文本文件中读取第一行?由于文件很大,我只想处理第一行。
嗯?我认为这样会简单得多。
set /p texte=< file.txt
echo %texte%
echo %texte:~3%
将跳过前三个字符。当您读取带有BOM的UTF-8文件时,这非常有用。 - KargWare命令的语法不正确。
第一行是#include <iostream>
。所以,显然,<
和>
符号破坏了它... 这不是最健壮的解决方案。 - ScienceDiscoverer这是一个通用的批处理文件,可以像GNU中的head
实用程序一样从文件中打印前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 的批处理文件行长度限制的影响。
for /f "usebackq eol= delims="
不会禁用 EOL
字符,它只会将其设置为 <SPACE>
。要禁用 EOL 的解决方案请参见 SO: Concatenate two strings...。 - jeb嗯,你们这些人......
C:\>findstr /n . c:\boot.ini | findstr ^1:
1:[boot loader]
C:\>findstr /n . c:\boot.ini | findstr ^3:
3:default=multi(0)disk(0)rdisk(0)partition(1)\WINNT
C:\>
findstr "^1:"
并获得双引号的温暖和保护。或者,如果你像我一样憎恨引号并想要冒险生活,可以使用 findstr /b 1:
。 - Amit Naidufindstr ^^1
。 - dbenhamset /p
解决方案更有效。 - Amit Naidu您可以尝试这个:
@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
)
"delims="
才能一起打印出带有空格的完整文件夹名称。 - GChuf感谢thetalkingwalnut提供的答案(Windows批处理命令读取文本文件第一行),我得出了以下解决方案:
@echo off
for /f "delims=" %%a in ('type sample.txt') do (
echo %%a
exit /b
)
powershell Get-Content file.txt -Head 1
这个比上面其他 PowerShell 示例要快得多,它只读取文件的一部分。
在其他人的回答基础上进行了一些扩展。现在可以指定要读取的文件和要将结果放入的变量:
@echo off
for /f "delims=" %%x in (%2) do (
set %1=%%x
exit /b
)
c:\> dir > test-file
c:\> getline variable test-file
c:\> set variable
variable= Volume in drive C has no label.
一行代码,与stdout重定向有用的">":
@for /f %%i in ('type yourfile.txt') do @echo %%i & exit
试试这个
@echo off
setlocal enableextensions enabledelayedexpansion
set firstLine=1
for /f "delims=" %%i in (yourfilename.txt) do (
if !firstLine!==1 echo %%i
set firstLine=0
)
endlocal
以下是使用 powershell
的解决方法:
powershell (Get-Content file.txt)[0]
你可以使用 powershell (Get-Content file.txt)[0..3]
轻松读取一系列行。
如果你需要在批处理脚本中将变量设置为 file.txt
的第一行,可以使用以下命令:
for /f "usebackq delims=" %%a in (`powershell ^(Get-Content file.txt^)[0]`) do (set "head=%%a")
为了测试,创建一个文本文件 test.txt
,至少有几行内容,并在同一文件夹中运行以下批处理文件(将文件命名为 .bat
扩展名):
@echo off
for /f "usebackq delims=" %%a in (`powershell ^(Get-Content test.txt^)[0]`) do (set "head=%%a")
echo Hello
echo %head%
echo End
pause
test.txt
的第一行内容为line 1
,你将会看到:Hello
line 1
End
Press any key to continue . . .