我试图从我的文本文件(其数据已按降序排序)中获取第一行(实际上是第一个数字),如下所示: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
如果我做错了事,请告诉我。 sorted.txt的长度每次都会变化,第一个值也会变化。但是始终必须获取最高编号(这将是第一行)。
我也尝试了以下PowerShell脚本:
powershell.exe -Command $lastnum = Get-Content -LiteralPath "C:\offsite\sorted.txt" | ForEach-Object { $Output += [Int]($_.Trim()) }
但是仍然无法正常工作。
最佳答案
您发布的代码应回显文字字符串“!lastnum!”。两次,因为您没有启用延迟扩展。但是即使启用了延迟扩展或将!
更改为%
,您也不会得到正确的结果,因为在赋值期间变量名和=
之间存在空格,这成为变量名(%lastnum %
)的一部分。
将代码更改为此:
set /p lastnum=<sorted.txt
echo %lastnum%
set /a "lastNum+=1"
echo %lastnum%
它会做您想要的。
或者,您可以使用像
for
这样的循环来仅读取文件的第一行:for /f "tokens=* delims=" %%a in (sorted.txt) do (
set "lastnum=%%~a"
goto continue
)
:continue
echo %lastnum%
set /a "lastNum+=1"
echo %lastnum%
在PowerShell中,您将使用以下内容:
[int]$lastnum = Get-Content 'sorted.txt' -TotalCount 1
Write-Output $lastnum
$lastnum++
Write-Output $lastnum
或像这样:
[int]$lastnum = Get-Content 'sorted.txt' | Select-Object -First 1
Write-Output $lastnum
$lastnum++
Write-Output $lastnum
关于powershell - 使用Windows批处理文件仅从文本文件中提取第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46133713/