如何在命令提示符中显示文本文件指定行(第3/7/19行)
Hey there! I see you're trying to pull specific lines (3rd, 7th, 19th) from your text file using Command Prompt, and the previous command only grabbed the first line. No worries—here's a modified script that will do exactly what you need:
@echo off setlocal enabledelayedexpansion set "target_lines=3 7 19" set "line_count=0" for /f "delims=" %%i in (mytext.txt) do ( set /a line_count+=1 for %%j in (%target_lines%) do ( if !line_count! equ %%j ( echo Line !line_count!: %%i ) ) ) endlocal
How this works:
- We enable delayed expansion so the
line_countvariable updates correctly inside the loop. - The
target_linesvariable holds the line numbers we want to extract—you can adjust this list easily if you need different lines later. - We increment
line_counteach time we read a line from the file. - For each line, we check if the current line number matches any of our target values. If it does, we echo that line (along with its number, though you can remove that part if you don't need it).
This script will handle special characters like !@$:/;" just fine because we're using "delims=" in the for /f command, which preserves the entire line without splitting it at spaces or other delimiters.
If you only want to display one specific line at a time (like just the 3rd line), you can simplify it even more:
@echo off setlocal enabledelayedexpansion set "target_line=3" set "line_count=0" for /f "delims=" %%i in (mytext.txt) do ( set /a line_count+=1 if !line_count! equ !target_line! ( echo %%i goto :eof :: Exit after finding the target line to save time ) ) endlocal
This version stops as soon as it finds the target line, which is more efficient if you only need one line.
内容的提问来源于stack exchange,提问作者Alexander

