Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Line (n) in a text file In Command Prompt

My text file include with 23 lines (lines include: !@$:/;" )

How can i only display line 3? in or 7? or 19?

I tried all commands was in stackoverflow

Example:

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

that's only show first line

like image 712
Alexander Avatar asked May 23 '18 14:05

Alexander


People also ask

What is command to display a line text?

Use the cat or nl command to display line numbers: cat -n hello.c nl hello.c.

How do I display the contents of a text file in command prompt?

In the Windows Command shell, type is a built in command which displays the contents of a text file. Use the type command to view a text file without modifying it.

What is %% A in CMD?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do I display a specific line in a file in Unix?

Use SED to display specific lines The -n suppresses the output while the p command prints specific lines.


2 Answers

@Compo has given a good answer. This is only to expound on it. Using aliases like GC should not be put into scripts. At the command line, sure, go ahead and reduce typing if you feel like it. Also, spelling out the parameter names provides more information and aids faster understanding.

To get only line 3.

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

Get-Content -Path '.\mytext.txt' -TotalCount 3 | Select-Object -Last 1

From the CMD console (Command prompt): (to get only line seven (7)

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

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

To get lines 3 through 7:

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

Or, in a cmd.exe batch script.

SET "FIRSTLINE=3"
SET "LASTLINE=7"
powershell -NoProfile -Command ^
    "Get-Content -Path '.\t.txt' -TotalCount %LASTLINE% |" ^
        "Select-Object -Last (%LASTLINE% - %FIRSTLINE% + 1)"
like image 130
lit Avatar answered Sep 28 '22 07:09

lit


@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

try with this bat (called lineNumber.bat) the first argument is the file you want to process the second is the line number:

call lineNumber.bat someFile.txt 5
like image 21
npocmaka Avatar answered Sep 28 '22 08:09

npocmaka