SShetty
SShetty

Reputation: 15

Fetch only first line from text file using Windows Batch File

I am trying to fetch the first line (in fact first number) from my text file (whose data has been sorted in descending order) as below:

sorted.txt:

10
9
8
7
6
5
4
3
2
1

But the output that I get is 1. I expected it to be 10.

I want to fetch this for further processing in a variable and the code that I used is as below:

set /p lastnum =< sorted.txt
pause
echo !lastnum!
pause
set /A lastNum = lastNum+1
echo !lastnum!
pause

Please let me know if I am doing something wrong. The length of the sorted.txt would vary everytime and the first value too. But always the highest number (which would be the first line) must be fetched.

I have tried the below PowerShell script too:

powershell.exe -Command  $lastnum = Get-Content -LiteralPath "C:\offsite\sorted.txt" | ForEach-Object { $Output += [Int]($_.Trim()) }

But still it is not working.

Upvotes: 1

Views: 5555

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

The code you posted should echo the literal string "!lastnum!" twice, because you don't enable delayed expansion. But even with delayed expansion enabled or changing the ! to % you wouldn't be getting the correct result because of the space between variable name and = during the assignments, which becomes part of the variable name (%lastnum %).

Change your code to this:

set /p lastnum=<sorted.txt
echo %lastnum%

set /a "lastNum+=1"
echo %lastnum%

and it will do what you want.

Alternatively you could use a for loop like this to read just the first line of the file:

for /f "tokens=* delims=" %%a in (sorted.txt) do (
  set "lastnum=%%~a"
  goto continue
)

:continue
echo %lastnum%

set /a "lastNum+=1"
echo %lastnum%

In PowerShell you'd use something like this:

[int]$lastnum = Get-Content 'sorted.txt' -TotalCount 1
Write-Output $lastnum

$lastnum++
Write-Output $lastnum

or like this:

[int]$lastnum = Get-Content 'sorted.txt' | Select-Object -First 1
Write-Output $lastnum

$lastnum++
Write-Output $lastnum

Upvotes: 4

Sage Pourpre
Sage Pourpre

Reputation: 10323

Using Powershell, your command call would look like this:

(Get-Content 'C:\offsite\sorted.txt').Split([environment]::newline)[0]

Upvotes: 0

Stephan
Stephan

Reputation: 56164

 set /p lastnum =< sorted.txt

sets a variable %lastnum % (or !lastnum ! with delayed expansion). The space before = gets part of the variable name. (A space after = in set var = val would get part of the value.)

(set /a works different: spaces are ignored.)

Upvotes: 2

Related Questions