Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string split with tab characters in PowerShell 1.0

I'm processing tab-separated text file (ANSI) in PowerShell 1.0, and for some reason I can't split text in the file into multiple fields using the split function. The code below always returns 1 although there are five values separated by tab in each line of the file.

$f = get-content ‘users.txt’
foreach ($line in $f)
{
   $fields = $line.split('\t')
   $fields.count | Out-Host
}

I tested split with other separators like pipe, comma and it worked without problems.

like image 225
kirill_l Avatar asked Oct 26 '11 19:10

kirill_l


People also ask

How do I split a string by characters in PowerShell?

Split() function. The . Split() function splits the input string into the multiple substrings based on the delimiters, and it returns the array, and the array contains each element of the input string. By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.

How do I split multiple delimiters in PowerShell?

Use Split operator to Split String by Multiple Delimiters in PowerShell. You can use the split operator to split the string into multiple substrings based on the multiple delimiters provided. In the above PowerShell script, the $str variable stores the string that contains multiple special characters.

How do you use tabs in PowerShell?

The TAB key has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB , it changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

What does @() mean in PowerShell?

Array subexpression operator @( )Returns the result of one or more statements as an array. The result is always an array of 0 or more objects. PowerShell Copy.


2 Answers

You're using the wrong escape character for the tab. Try this instead:

$f = Get-Content "Users.txt"

foreach ($line in $f) {
    $fields = $line.Split("`t")
    $fields.Count | Out-Host
}
like image 160
Tom H Avatar answered Sep 18 '22 02:09

Tom H


(Get-Content -LiteralPath C:\temp\Users.txt) | ForEach-Object {$_.Split("`t")} | Set-Content -Path C:\temp\Results.txt
like image 30
user3177926 Avatar answered Sep 18 '22 02:09

user3177926