$content = @'
some text
line 1: [1]
line 2: id = Item
line 1: [2]
line 2: id = Item
line 1: [123]
line 2: id = Item
'@ -split '\r?\n'
switch -Regex ($content) {
'(?<=\[)[^\]]+' {
# capture whats between brackets
$value = $Matches[0]
# output the line
$_
# go to next line
continue
}
# if there was a capture previously
{ $value } {
# replace the end of the line including
# any possible whitespaces before it
# with a space and the captured value
$_ -replace '\s*$', " $value"
# reset the value
$value = $null
# go to next line
continue
}
# output this line if none of the above
Default { $_ }
}
如果你正在阅读一个文件,你可以使用-File参数,逻辑仍然是一样的:
# this outer scriptblock allows us to pipe the output
# from the switch to Set-Content
& {
switch -Regex -File $filepath {
# same logic here
}
} | Set-Content path\to\resultfile.ext
1条答案
按热度按时间gojuced71#
例如,带有
-Regex
标志的switch
可用于此目的:如果你正在阅读一个文件,你可以使用
-File
参数,逻辑仍然是一样的: