在命令提示符下显示文本文件中的行 (n)



我的文本文件包含 23 行(行包括:!@$:/;" (

如何只能显示第 3 行? in 或 7? 或 19?

我尝试所有命令都在堆栈溢出中

例:

setlocal enabledelayedexpansion
@echo off
for /f "delims=" %%i in (mytext.txt) do (
if 1==1 (
set first_line=%%i
echo !first_line!
goto :eof
))

那只是显示第一行

@Compo给出了一个很好的答案。这只是为了阐述它。不应将像GC这样的别名放入脚本中。当然,在命令行中,如果您愿意,请继续减少键入。此外,拼写参数名称可提供更多信息并有助于更快地理解。

仅获取第 3 行。

GC .mytext.txt -T 3|Select -L 1
Get-Content -Path '.mytext.txt' -TotalCount 3 | Select-Object -Last 1

从 CMD 控制台(命令提示符(:(仅获取第七行 (7(

PowerShell "GC .mytext.txt -T 7|Select -L 1"
PowerShell -NoProfile "Get-Content -Path '.mytext.txt' -TotalCount 7 | Select-Object -Last 1"

要获取第 3 行到第 7 行,请执行以下操作:

$FirstLine = 3
$LastLine=7
powershell -NoProfile -Command "Get-Content -Path '.t.txt' -TotalCount $LastLine | Select-Object -Last ($LastLine - $FirstLine + 1)"

或者,在 cmd.exe 批处理脚本中。

SET "FIRSTLINE=3"
SET "LASTLINE=7"
powershell -NoProfile -Command ^
"Get-Content -Path '.t.txt' -TotalCount %LASTLINE% |" ^
"Select-Object -Last (%LASTLINE% - %FIRSTLINE% + 1)"
@echo off
setlocal
set "FILE_TO_PROCESS=%~f1"
set /a LINE_NUMBER=%~2
set /a trim=LINE_NUMBER-1
break>"%temp%empty"&&fc "%temp%empty" "%FILE_TO_PROCESS%" /lb  %LINE_NUMBER% /t |more +4 | findstr /B /E /V "*****"|more +%trim%
endlocal

尝试使用此蝙蝠(称为 lineNumber.bat(第一个参数是您要处理的文件,第二个参数是行号:

call lineNumber.bat someFile.txt 5

有几种方法可以做到这一点。您的第一个选择是正常通过for循环,并在到达所需行后断开循环。

@echo off
:: Specify which line to return
set get_line=7
:: Skip all lines before it, then print the next line and abort
set /a get_line-=1
for /F "skip=%get_line% delims=" %%A in (mytext.txt) do (
echo %%A
goto :end_loop
)
:end_loop

另一种选择是将不需要的行之前的所有行存储在 temp 变量中,然后显示下一行。

@echo off
setlocal enabledelayedexpansion
:: Specify which line to return
set get_line=7
:: Skip all lines before it, then print the next line and abort
set /a get_line-=2
(
for /L %%A in (0,1,%get_line%) do set /p skip_line=
set /p return_line=
) <file.txt
echo !return_line!

请注意,第一个选项不适合返回脚本的第一行。

既然你说了"显示",为什么不试一试PowerShell

从 PowerShell 控制台:

GC .mytext.txt -T 3|Select -L 1

从 CMD 控制台(命令提示符(:

PowerShell "GC .mytext.txt -T 7|Select -L 1"

从批处理文件:

@(PowerShell "GC .mytext.txt -T 19|Select -L 1"&Pause)

最新更新