【问题标题】:String replacement to variable字符串替换变量
【发布时间】:2013-02-16 05:14:24
【问题描述】:

我有以下有效的脚本,我正在尝试以更有效的方式重写。下面的代码行工作并完成我想要的:

Get-Content "C:\Documents and Settings\a411882\My Documents\Scripts\printserveroutput.txt" | Select-String -SimpleMatch -AllMatches -Pattern "/GPR" | % {
    $_.Line -replace '(?:.*)(/GPR)(?:.*)(?<=on\s)(\w+)(?:.*)', '$1,$2'
}

Get-Content "C:\Documents and Settings\a411882\My Documents\Scripts\printserveroutput.txt" | Select-String -SimpleMatch -AllMatches -Pattern "DV6" | % {
    $_.Line -replace '(?:.*)(DV6)(?:.*)(?<=on\s)(\w+)(?:.*)', '$1,$2'
}

我将完全相同的代码行重复七次,但会稍微改变我要查找的内容。我得到的输出如下,我想要的(注意:这只是一个小输出):

/GPR,R3556
/GPR,R3556

虽然这行得通,但我真的不喜欢代码的混乱程度,因此我决定尝试以更有效的方法重新编写它。我已经重新编写了这样的代码:

$My_Arr = "/GPR", "DV6", "DV7", "RT3", "DEV", "TST", "PRE"
$low = $My_Arr.getlowerbound(0)
$upper = $My_Arr.getupperbound(0)
for ($temp=$low; $temp -le $upper; $temp++){
    $Test = $My_Arr[$Temp]
    Get-Content "C:\Documents and Settings\a411882\My Documents\Scripts\printserveroutput.txt" | Select-String -SimpleMatch -AllMatches -Pattern $My_Arr[$temp] | % {
    $_.Line -replace '(?:.*)($Test)(?:.*)(?<=on\s)(\w+)(?:.*)', '$1,$2'
    }
}

这给我的输出如下:

10         Document 81, A361058/GPR0000151814_1: owned by A361058 was printed on R3556 via port IP_***.***.***.***.  Size in bytes: 53704; pages printed: 2                                                                  20130219123105.000000-300  
10         Document 80, A361058/GPR0000151802_1: owned by A361058 was printed on R3556 via port IP_***.***.***.***.  Size in bytes: 53700; pages printed: 2                                                                  20130219123037.000000-300  

这几乎是正确的,但是 -replace 行是我的错误发生的地方,因为代码在到达 ($Test) 时需要一个字符串而不是变量。它会发布我每次在此示例中找到 /GPR 时解析的文本文件的整行,而不是上面显示的所需输出。有人知道修复这条线并获得与我使用的原始代码相同的输出的方法吗?

编辑:我现在使用更新的代码得到的输出也是我试图解析的 .txt 文件中的确切文本。 .txt 中的行数比 .txt 中的要多,但在大多数情况下,它与 .txt 中的行数相同。我只关心在数组中获取 /GPR 或任何其他可能的字符串,然后是每次在单词“on”之后的服务器名称。

【问题讨论】:

  • 你能发一个匹配的原文样本吗?
  • 您从第二行代码获得的输出正是要匹配的原始文本。对不起,应该提到它更清楚。
  • 我不明白“第二行代码”是什么意思。您正在从我没有的文件中读取输入.....
  • 没关系。我明白了。

标签: arrays parsing powershell powershell-2.0


【解决方案1】:

我会说这是由简单的引号引起的,它可以防止变量扩展。 PS 正在尝试替换确切的字符串'(?:.*)($Test)(?:.*)(?&lt;=on\s)(\w+)(?:.*)',而不用其值替换 $test 变量。 尝试用引号替换它们,但在第二个字符串上保留简单的引号,如下所示:

Get-Content "C:\Documents and Settings\a411882\My Documents\Scripts\printserveroutput.txt" | Select-String -SimpleMatch -AllMatches -Pattern $My_Arr[$temp] | % {
    $_.Line -replace "(?:.*)($Test)(?:.*)(?<=on\s)(\w+)(?:.*)", '$1,$2'

【讨论】:

    【解决方案2】:

    这对您的数据有效吗?

    $file = 'C:\Documents and Settings\a411882\My Documents\Scripts\printserveroutput.txt'
    $regex = '(?:.*)(/GPR|DV6|DV7|RT3|DEV|TST|PRE)(?:.*)(?<=on\s)(\w+)(?:.*)'
    (Get-Content $file) -match $regex -replace $regex,'$1,$2'
    

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 2020-02-04
      • 2018-01-01
      • 1970-01-01
      相关资源
      最近更新 更多