bbcompent1
bbcompent1

Reputation: 494

PowerShell strip all characters after first tab

I have a file I am trying to import from. The first column is an IDnum, Second is Name, Third is Version. What I want is just the IDNum column. The file is tab delimited so I was wondering how do I capture only the first column before the tab? The rest of the text on each line is not needed. The line looks like this:

4809490 WebGoat 5.0

So in this example, I only want 4809490. I do not need the rest of that stuff.

Upvotes: 1

Views: 1811

Answers (3)

LukStorms
LukStorms

Reputation: 29647

This can be done via Select-String as a one-liner.

Select-String -Path file.txt -Pattern '^\w+' -AllMatches |%{$_.Matches.Value} > newfile.txt

Upvotes: 1

bbcompent1
bbcompent1

Reputation: 494

I sat back and thought about it and found a way myself too :)

ForEach ($line in $content) { 
$thisappid = $line.Split("`t")
Write-Host $thisappid.GetValue(0)
}

Those are good answers as well so thank you!

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 58921

You can either use the Import-CSV with a specified tab delimiter to load the file and select only the first column, or you can use the Get-Content cmdlet to load the file, iterate over it using ForEach-Object and use a regex to extract the ID:

Get-Content 'PATH_TO_YOUR_FILE' | ForEach-Object { 
    [regex]::Match($_, '\d+').Groups[0].Value 
}

Upvotes: 0

Related Questions