Consider the ASCII text file test1.txt
:
a,b,c
d,e,f
And the following Powershell Script test1.ps1
:
$input -split "`n" | ForEach-Object {
$row = $_ -split ","
$row[0]
}
The output is, as excpected:
a
d
However, if we change the separator to |
everything fails as in test2.txt
:
a|b|c
d|e|f
And the following Powershell Script test2.ps1
:
$input -split "`n" | ForEach-Object {
$row = $_ -split "|"
$row[0]
}
The output is all but empty. Why does the -split
fail?
It seems -split
expects a regular expression and thus you need to escape the pipe as in:
$row = $_ -split "\|"
Or specify the SimpleMatch
option to split on the literal string or character:
$row = $_ -split "|", 0, "SimpleMatch"
The 0
stands for MaxSubstrings: "The maximum number of substrings, by default all (0)."
Source: http://ss64.com/ps/split.html
Also: Get-Help about_Split
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With