windows 如何将foreach的结果输出到文件?

wgeznvg7  于 2022-11-26  发布在  Windows
关注(0)|答案(1)|浏览(245)

我有这个脚本来修剪前导空格,从一个txt文件中删除“和”,但是我不能把结果放到输出文件中

$text = Get-Content output.txt
$text -replace '["]','' -replace '[,]','' | Foreach {write-host $_.TrimStart()}

这是我得到的结果。我想把它输出到一个文件上,而不是像这样显示。

PS C:\Users\aa1\temp> $text -replace '["]','' -replace '[,]','' | Foreach {write-host $_.TrimStart()}
AutoScalingGroupName: asg1
MinSize: 1
AutoScalingGroupName: asg2
MinSize: 1
AutoScalingGroupName: asg3
MinSize: 1
AutoScalingGroupName: asg4
MinSize: 1
AutoScalingGroupName: asg5
MinSize: 3
PS C:\Users\aa1\temp>
tvz2xvvm

tvz2xvvm1#

如果使用参数-Raw而不是字符串数组将文件的内容作为一个多行字符串读取,则可以在不使用如下循环的情况下执行所有替换:

(Get-Content -Path 'output.txt' -Raw) -replace '(?m)[",]|^\s+' | Set-Content -Path 'output.txt'

正则表达式详细信息:

Match this alternative (attempting the next alternative only if this one fails)
   (?        Use these options for the whole regular expression
      m      ^$ match at line breaks
   )        
   [",]      Match a single character from the list “",”
|           
             Or match this alternative (the entire match attempt fails if this one fails to match)
   ^         Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed)
   \s        Match a single character that is a “whitespace character” (any Unicode separator, tab, line feed, carriage return, vertical tab, form feed, next line)
      +      Between one and unlimited times, as many times as possible, giving back as needed (greedy)

相关问题