3

我在 Perl 中无数次使用过这种东西:

for ( $someVariable ) {
    s/findthis/replaceitwiththis/g;
    s/findthat/replaceitwithsomethingelse/g;
}

的值$someVariable暂时在$_,变量“就地”更新;每个新的替换命令都会继续更新/覆盖变量的内容。这是在一个简单的循环中完成大量更改的一种方便且紧凑的方法。

Powershell 是否具有与“for”等价的用法?

在@neolisk 的回复之后添加评论,以便我可以使用格式。

$s = 'abcde'
$s | foreach {
    $_ -replace 'a','x'
    $_ -replace 'e','z'
}
write-host "And: $s"

屏幕上看到的结果:

xbcde
abcdz
And: abcde

也试过$_ = $_ -replace 'a','x'等等。这里必须有一些额外的语法才能获得“就地”替换......

在@Nacht 回复后进一步编辑。这行得通,尽管我对反引号并不感到疯狂:

$s = 'now is the time for all good individuals blah blah'
Write-Host $s
$s = $s `
  -replace "now", 'NEVER' `
  -replace 'time', 'moment' `
  -replace "blah\s+blah", '-- oh, WHATEVER'
Write-Host $s

输出:

now is the time for all good individuals blah blah
NEVER is the moment for all good individuals -- oh, WHATEVER
4

3 回答 3

3

It is exactly like this in Powershell, but the syntax is slightly different:

$someVariable | foreach {
    Write-Host $_;
}

If you want to do in-place replace, keep in mind that $_ is immutable, i.e. readonly. The proper way would be to output new string on pipeline and collect into another variable, so for your example it can look like this:

$s = 'abcde' 
$newS = $s | foreach {
    $_ -replace 'a','x' -replace 'e','z'    
}
write-host "And: $newS";
于 2012-11-13T02:53:00.410 回答
0

我不知道在这里以这种方式回答我自己的问题是否合适。如果不是,请指教。总结几种方法(全部选中):

$s = 'abcde' (likewise for all below)
$s | foreach {
    $_ `
    -replace 'a', 'X' `
    -replace 'e', 'Z'
}

XbcdZ在执行期间显示。$s不变

$s = $s `
    -replace 'a', 'X' `
    -replace 'e', 'Z'

$s 已“就地”更新;现在的价值XbcdZ

$t = $s | foreach {
    $_ `
    -replace 'a', 'X' `
    -replace 'e', 'Z'
}

$s不变。$t 的值:XbcdZ

$t = $s `
  -replace 'a', 'X' `
  -replace 'e', 'Z'

$s 不变。$t 的值:XbcdZ

($t = $s) `
  -replace 'a', 'X' `
  -replace 'e', 'Z'
Write-Host "`$s: $s -- `$t: $t"

添加了括号以查看可能发生的情况。
两个变量的值都不会改变。打印到通过 Write-Host 打印的行上方XbcdZ的控制台。

于 2012-11-13T22:39:01.647 回答
0

这是你要找的吗?

$s = 'abcde'
$s = $s -replace 'a','x' -replace 'e','z'
write-host "And: $s"

输出:

And: xbcdz

你也可以像这样在几行上做到这一点:

$s = 'abcde'
$s = $s -replace 'a','x'
$s = $s -replace 'e','z'
write-host "And: $s"

以下不起作用,因为每一行都是单独输出的:

$s | foreach {
    $_ -replace 'a','x'
    $_ -replace 'e','z'
}

以下不起作用,因为赋值语句不输出任何内容:

$s | foreach {
    $_ = $_ -replace 'a','x'
}
于 2012-11-13T03:56:28.287 回答