简体   繁体   English

每行每n个地方添加一个定界符

[英]Adding delimiter every n places in every line

How can I extend this script to add delimiters in every line. 如何扩展此脚本以在每行中添加定界符。

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

Is the foreach code like this? foreach代码是这样的吗?

$x| %{@( ($_[0..4] -join ''), ($_[5..10] -join ''), 
($_[11..17] -join ''),
($_[18..21] -join ''))}??

And suddenly it is clear what you want. 突然间,您就清楚了想要什么。

Long form: 长表:

$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
}

Short form: 简写:

gc somefile.txt | % { "$($_[0..4] -join '')|$($_[5..10] -join '')|$($_[11..17] -join '')|$($_[18..21] -join '')" } >> somenewfile.txt

I got rid of the building an array and joining it, and replaced it with string expansion where the string has the delimiters in it; 我摆脱了建立一个数组并将其连接的问题,并用字符串扩展替换了它,其中字符串中有定界符。 for viewers, the pattern is: 对于观众来说,模式是:

"$()|$()|$()"  #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

我将REGEX用于此类工作,以避免零件不同长度的问题:

Get-Content .\somefile.txt | % { $_ -replace '(\D*[^\d]*)(\d*[^\D]*)(.+)','$1 $2 $3' }

another solution with regex: 正则表达式的另一个解决方案:

(cat file) -replace '\d+|\D+','$0 '

apple 123456 NewYorkCity
nissan 98766 BostonMA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM