Powershell 拆分基于新行
Powershell Split based on new line
我有一个使用 Get-Content
导入的文本文件
它看起来像这样:
aago go sdf
bbbgo go sdf gojh
go
zzzz bbb
go
sdkfgo go sdfd
go
我想 -split
它基于 'go' 它是单行“go”,也就是我只想要 3 个数组项。所以 -split 'go'
不会起作用。
如何为 'go' 行中唯一的项目或 'go' 之后有一个新行的拆分指定分隔符?
所以我期望的输出是这样的
$output[0]=
"aago go sdf
bbbgo go sdf gojh
"
$output[1]=
"zzzz bbb
"
$output[2]=
"sdkfgo go sdfd
"
# Sample input, defined via a verbatim here-string.
$str = @'
aago go sdf
bbbgo go sdf gojh
go
zzzz bbb
go
sdkfgo go sdfd
go
'@
$str -split '(?m)^go\s*$' -ne '' | # Split as desired.
ForEach-Object { "«$_»" } # Visualize the results
对于 regex used with the -split
operator above and the ability to experiment with it, see this regex101.com page 的解释。
输出:
«aago go sdf
bbbgo go sdf gojh
»
«
zzzz bbb
»
«
sdkfgo go sdfd
»
我有一个使用 Get-Content
导入的文本文件
它看起来像这样:
aago go sdf
bbbgo go sdf gojh
go
zzzz bbb
go
sdkfgo go sdfd
go
我想 -split
它基于 'go' 它是单行“go”,也就是我只想要 3 个数组项。所以 -split 'go'
不会起作用。
如何为 'go' 行中唯一的项目或 'go' 之后有一个新行的拆分指定分隔符?
所以我期望的输出是这样的
$output[0]=
"aago go sdf
bbbgo go sdf gojh
"
$output[1]=
"zzzz bbb
"
$output[2]=
"sdkfgo go sdfd
"
# Sample input, defined via a verbatim here-string.
$str = @'
aago go sdf
bbbgo go sdf gojh
go
zzzz bbb
go
sdkfgo go sdfd
go
'@
$str -split '(?m)^go\s*$' -ne '' | # Split as desired.
ForEach-Object { "«$_»" } # Visualize the results
对于 regex used with the -split
operator above and the ability to experiment with it, see this regex101.com page 的解释。
输出:
«aago go sdf
bbbgo go sdf gojh
»
«
zzzz bbb
»
«
sdkfgo go sdfd
»