比较一行文本中的两个值,然后根据结果执行条件任务

Compare two values from a line of text then perform conditional task based on result

提问人:JeffTTI 提问时间:10/31/2023 最后编辑:DanielJeffTTI 更新时间:11/1/2023 访问量:35

问:

我是 PowerShell 的新手,只编写了几个基本脚本。 这是我正在尝试做的: 对于下面的文本行,我想比较每行末尾的两个值(请参阅下面的pstest.txt)(50,20 line3;20,50 line4),如果第一个值高于第二个值,则替换该行上的文本。

我已经研究了几种可能的方法,但找不到适合这种情况的方法。

到目前为止,我已经找到了替换特定文本的解决方案,并且已经找到了一种从特定行中检索值进行比较的方法,但不确定如何从这里开始。 我的目标是只修改第一个“维度”大于第二个“维度”的线。 当条件为真时,在“5-STD”后面添加“T”,并修剪行尾。 然后将文件写在原始文件上。 下面是我的脚本,到目前为止,我包含了 pstest.txt 文件的副本以供参考。

# $content = Get-Content "c:\temp\pstest.txt"
$line3 = Get-Content "c:\temp\pstest.txt" | Select-Object -Index 2 # get 1st line item (first 2 lines ignored)
$line4 = Get-Content "c:\temp\pstest.txt" | Select-Object -Index 3 # get 2st line item
$value1 = $line3.Substring(129,2) # gets the 1st dimension value from the 1st line item
$value2 = $line3.Substring(133,2) # gets the 2nd dimension value from the 1st line item
$value3 = $line4.Substring(129,2) # gets the 1st dimension value from the 2nd line item
$value4 = $line4.Substring(133,2) # gets the 2nd dimension value from the 2nd line item
Write-Host $value1, $value2 # displays values - test only
Write-Host $value3, $value4 # displays values - test only
# $content | ForEach-Object {$_ -replace '"5-STD", ', '"5-STD",T'} | Set-Content "C:\temp\test.txt"

诗行:.txt

<V1.0>, "WinIG Import File"
*, "0918230406", "", "0918230406", "091823", "", ""
1, 1, 0, "CLAC-DSB-A", 50, 50, 0.875, "", "", "", "", 0.0, 0.0, "", "", "", "25504-6-1-IGU-TRAP 108279-1", "5-STD", , , 0.0, 20, 50, 20
2, 1, 0, "CLAC-DSB-A", 50, 50, 0.875, "", "", "", "", 0.0, 0.0, "", "", "", "25504-6-2-IGU-TRAP 108279-2", "5-STD", , , 0.0, 20, 20, 50
PowerShell 比较

评论


答:

0赞 mklement0 11/1/2023 #1

使用带有 和 参数的 switch 语句进行基于正则表达式的逐行处理:-File-Regex

& {
  switch -Regex -File in.txt {
    '^(.+), (\d+), (\d+)$' {
      if ([int] $Matches.2 -gt [int] $Matches.3) {
        $Matches.1 + ',T'
      } else {
        $_ # pass through
      }
    }
    default { $_ } # pass through
  }
} |
  Set-Content out.txt

注意:

  • 上面假设所有以两个逗号分隔的十进制数结尾的行都是感兴趣的。

  • 正则表达式匹配这些行,并通过捕获组 () 捕获感兴趣的子字符串,结果反映在自动$Matches变量中,其中包含第一个捕获组匹配的内容,第二个捕获组,依此类推。^(.+), (\d+), (\d+)$(...)$Matches.1$Matches.2

  • switch,由于是关键字(语言语句),不能直接用作管道输入,因此需要将其包含在脚本块 () 中,该脚本块 () 通过调用运算符调用{ ... }&

    • 如果首先收集所有输出是可以接受的,您可以更简单地写:

      # ... represent the `switch` statement above. 
      Set-Content out.txt $(...)
      
  • 请注意,一般来说,可能需要将参数与 Set-Content 一起使用,因为输入文件的特定字符编码永远不会保留在 PowerShell 管道中(内容始终解码为 .NET 字符串,而不存储有关原始编码的信息)。-Encoding

    • 在保存(返回)到文件时,将应用所选 cmdlet 的 / 重定向运算符的默认编码。
    • 不幸的是,Windows PowerShell 中的默认值因 cmdlet 而异(特别是 ANSI for 和 UTF-16LE(“Unicode”) for /),而 PowerShell (Core) 7+ 现在明智地默认为(无 BOM)UTF-8。Set-ContentOut-File>