如何扩展此脚本以在每行中添加分隔符。
apple123456NewYorkCity
nissan98766BostonMA
...
...
$x = somefile.txt
$y = @( ($x[0..4] -join ''), ($x[5..10] -join ''),
($x[11..17] -join ''),
($x[18..21] -join ''))
$z = $y -join '|'
$z > somenewfile.txt
foreach代码是这样的吗?
$x| %{@( ($_[0..4] -join ''), ($_[5..10] -join ''),
($_[11..17] -join ''),
($_[18..21] -join ''))}??
答案 0 :(得分:0)
突然间你很清楚你想要什么。
长篇:
$lines = Get-Content "somefile.txt"
ForEach ($x in $lines) {
$y = "$($x[0..4] -join '')|$($x[5..10] -join '')|$($x[11..17] -join '')|$($x[18..21] -join '')"
$z = $y -join '|'
Write-Output $z | Out-File -FilePath "somenewfile.txt" -Append
}
简短形式:
gc somefile.txt | % { "$($_[0..4] -join '')|$($_[5..10] -join '')|$($_[11..17] -join '')|$($_[18..21] -join '')" } >> somenewfile.txt
我摆脱了构建数组并加入它,并将其替换为字符串扩展,其中字符串中包含分隔符;对于观众来说,模式是:
"$()|$()|$()" #expressions in a string, separated by bars
"$($_[0..4] -join '')|.." #each expression is taking characters
#and joining the resulting array into a string
#$_.SubString(n,m) would return a string directly
#but it complains if you go past the end of the
#string, whereas $_[n..m] does not
答案 1 :(得分:0)
我会使用REGEX来完成这类工作,以避免不同部分长度的问题:
Get-Content .\somefile.txt | % { $_ -replace '(\D*[^\d]*)(\d*[^\D]*)(.+)','$1 $2 $3' }
答案 2 :(得分:0)
使用正则表达式的另一种解决方案:
(cat file) -replace '\d+|\D+','$0 '
apple 123456 NewYorkCity
nissan 98766 BostonMA