powershell - 使用Windows批处理文件仅从文本文件中提取第一行

标签 powershell batch-file

我试图从我的文本文件(其数据已按降序排序)中获取第一行(实际上是第一个数字),如下所示:
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/

相关文章:

windows - PowerShell 脚本 "Get-VMHost Hardware.SystemInfo.OtherIdentifyingInfo"将返回 2 个服务标记值

powershell - 如何在 Pester 中使用 'get arguments for calls made on' 模拟(或以其他方式生成包含实际值和预期值的有用消息)?

batch-file - 为什么 'Run as administrator' 会更改(有时)批处理文件的当前目录?

iis-7 - 通过 Powershell 将用户分配给 IIS AppPool

PowerShell:创建本地用户帐户

Azure PS 查询获取特定于给定资源组注册的资源提供程序

postgresql - 在 Windows 中使用 .bat 备份 Postgresql

batch-file - 复制到所有文件夹批处理文件?

Android - 在没有开发人员选项的情况下使用 ADB

batch-file - 复制bat文件中的多个文件