0%

如何提取指定行的内容?

比如有一5行的文件,需要读取第3行的内容,文件名为test.txt

SHELL:

  1. ```
    awk ‘NR == 3{ print; exit; }’ test.txt

    1
    2
    3

    2. ```
    sed -n '3{ p; q; }' test.txt
  2. ```
    head -3 test.txt |tail -1

    1
    2
    3
    4

    ## CMD:

    1. for循环读取

    for /f “tokens=1,2* delims=:” %%i in (‘findstr /n .* test.txt’) do if %%i==3 echo %%j

    1
    2
    3
    4
    5
    6

    2. 使用"小函数"读取特定行:`Call ReadLine2.bat <文件名> <读取行号>`

    例如:"`Call ReadLine2 test.txt 11 5 7 9`",可以读取test.txt文件的第5、7、9和11行,后面的行号不分先后大小顺序。但是效率不是很高,读取小文件还是可以的。

    >`Call ReadLine2 test.txt 3`

    @echo off&SetLocal ENABLEDELAYEDEXPANSION
    :::::::::::ReadLine2.Bat::::::::::::::::::
    if “%1”==”” (goto –help) else (set file=%1)
    if not exist %file% goto :eof
    if “%2”==”” (
    for /f “tokens=1* delims=:” %%a in (‘findstr /n .* “%file%”‘) do echo/%%b
    goto :eof
    ) else (
    set args=%*
    for %%a in (!args!) do (
    if not “%%a”==”%1” (for /f “tokens=1* delims=:” %%b in (‘findstr /n .* “%file%”‘) do (
    if “%%b”==”%%a” echo/%%c)
    )
    )
    )
    goto :eof

:–help
echo/======================================
echo/本程序段需要带参数才能正常运行
echo/&echo/Usage:&echo/Call ReadLine2 ^<文件名^> ^<读取行号^>
echo/&echo/例如:Call ReadLine2 aa.txt 5 7 11 ,将读取aa.txt文件的第5,7,11行
echo/&echo/如果^<读取行号^>没有指定,将读取整个文件的内容
echo/======================================
goto :eof

1
2
3
4
5
6

3. 使用"小函数"读取特定行:`Call ReadLine.bat <文件名> <跳过的行数> <读取行数>`

例如:"`Call ReadLine test.txt 5 7`",那么将跳过test.txt文件的前5行,显示下面的7行字符,也包含空行。也可以不指定第三个参数。

>`Call ReadLine test.txt 2 1`

@echo off&SetLocal ENABLEDELAYEDEXPANSION
if “%1”==”” (goto –help) else (set file=%~s1)
if “%2”==”” (set first=”delims=: tokens=1*”) else (set first=”skip=%2 delims=: tokens=1*”)
if “%3”==”” (
for /f %first% %%a in (‘findstr /n .* %file%’) do echo/%%b
goto :EOF
)
set last=%3
set loop=0
for /f %first% %%a in (‘findstr/n .* %file%’) do (
if not defined lxmxn (echo/%%b&set /a loop+=1) else (goto :EOF)
if “!loop!”==”%last%” set lxmxn=Nothing
)
GOTO :EOF:–help
echo/======================================
echo/本程序段需要带参数才能正常运行
echo/&echo/Usage:&echo/Call ReadLine ^<文件名^> ^<跳过行数^> ^<读取行数^>
echo/&echo/例如:call ReadLine aa.txt 5 7 ,将跳过aa.txt文件的前5行,读取下面的7行字符
echo/&echo/如果^<跳过行数^>没有指定,就从文件第一行读取
echo/&echo/指定^<读取行数^>时必须指定^<跳过行^>
echo/======================================
goto :eof
```