I'ld use REGEX for this kind of job, to avoid problems with different parts lenghts:
Get-Content .\somefile.txt | % { $_ -replace '(\D*[^\d]*)(\d*[^\D]*)(.+)','$1 $2 $3' }
题
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?
$x| %{@( ($_[0..4] -join ''), ($_[5..10] -join ''),
($_[11..17] -join ''),
($_[18..21] -join ''))}??
解决方案
I'ld use REGEX for this kind of job, to avoid problems with different parts lenghts:
Get-Content .\somefile.txt | % { $_ -replace '(\D*[^\d]*)(\d*[^\D]*)(.+)','$1 $2 $3' }
其他提示
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
another solution with regex:
(cat file) -replace '\d+|\D+','$0 '
apple 123456 NewYorkCity
nissan 98766 BostonMA