【问题标题】:Math from a file.txt来自 file.txt 的数学
【发布时间】:2022-01-04 13:07:33
【问题描述】:
    $space =("`r`n")
    $data = @(Get-Content C:\Users\user1\Desktop\ma.txt)
    $Array = ($Data.Split($space)).Split($space)
    $pos1 = $Array[0][0]+$Array[0][1]
    $pos2 = $Array[1][0]+$Array[1][1]
    $pos3 = $Array[2][0]+$Array[2][1]
    #$pos1
    #$pos2 
    #$pos3
    $zahl1 = $Array[0][5]+$Array[0][7]+$Array[0][9]
    $zahl1

PowerShell 7.2

txt1.txt 有文字:

x1 = 2 + 3

x2 = 8 / 4

x3 = 1 - 4

我希望使用终端中的命令将结果(来自 x1、x2、x3)保存在 txt2.txt 中。 我试过数组, 但我只得到 :2+3 而不是 5

有什么想法吗?

【问题讨论】:

  • 我可以使用 math.ps1 -replace .\text1.txt , .\text2.txt 吗?在终端?我的目标是(仅)在终端中调用 math.ps1 并在终端中将 txt1 替换为 txt2
  • 所以脚本中不需要写Get-Content -Path text1.txt 或|设置内容-路径 text2.txt

标签: arrays powershell


【解决方案1】:

您可以为此使用 Invoke-Expression,但 read the warning first

Get-Content -Path text1.txt | Where-Object {$_ -match '\S'} | ForEach-Object {
    $var,$calculation = ($_ -split '=').Trim()
    '{0} --> {1}' -f $var, (Invoke-Expression -Command $calculation)
} | Set-Content -Path text2.txt

【讨论】:

  • @Pante 请问您为什么决定不接受我的回答?
【解决方案2】:

这是一个更安全版本的尝试,它只匹配数学表达式,因此用户无法通过Invoke-Expression运行任意代码:

Get-Content text1.txt | 
    Select-String '^\s*(\S+)\s*=([\d\.+\-*/%\(\)\s]+)$' | 
    ForEach-Object {
        $var        = $_.Matches.Groups[ 1 ].Value
        $expression = $_.Matches.Groups[ 2 ].Value
        $result     = Invoke-Expression $expression
        "{0} = {1}" -f $var, $result
    } | 
    Set-Content text2.txt

Select-String cmdlet 使用正则表达式仅匹配被视为“安全”的行。在 RegEx 中定义了两个组,将行拆分为变量 (1) 和计算 (2) 子字符串。然后通过$_.Matches.Groups提取这些。

RegEx 细分:

Pattern Description
^ line start
\s* zero or more whitespace characters
( start 1st capturing group
\S+ one or more non-whitespace characters
) end 1st capturing group
\s* zero or more whitespace characters
= literal "="
( start 2nd capturing group
[ start list of allowed characters
  \d\.+\-*/%\(\)\s digits, dot, math ops, parentheses, whitespace
] end the list of allowed characters
+ one or more chars (from the list of allowed characters)
) end 2nd capturing group
$ line end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-05
    • 2018-06-22
    • 1970-01-01
    • 2016-12-12
    • 2019-06-18
    • 2017-05-16
    • 2020-09-08
    • 1970-01-01
    相关资源
    最近更新 更多