HamTheAstroChimp
HamTheAstroChimp

Reputation: 1425

How to read last word in text file using powershell(1.0)?

I've a text file content like below,


     123    123   123   123   123   Exchange

i want that last word "Exchange", need solution in powershell. please help me.

Note: beginning of the file is TAB, also between the Character.

Thanks, RaM

Upvotes: 0

Views: 2338

Answers (3)

Dave Sexton
Dave Sexton

Reputation: 11188

How about this one-liner:

[Regex]::Match((Get-Content .\file_name.txt) -Join ' ', '(\w+)[^\w]*$').Groups[1].Value

Not sure if you have -Join available on Powershell v1, if so then this:

$t = '';Get-Content .\file_name.txt | % {$t += " $_"};[Regex]::Match($t, '(\w+)[^\w]*$').Groups[1].Value

Upvotes: 1

Richard
Richard

Reputation: 7000

This Function will take a text file path and return the last word of a last line of text file. It will ignore any blank line that may be in the text file.

Function Get-Last-Word($path){ 
    $file = (Get-Content $path | Measure-Object)
    $numberOfLines = $file.Count
    $numberOfWords = (Get-Content $path | Select -Index ($numberOfLines -1) | Measure-Object -word)
    $Line = Get-Content $path | Select -Index ($numberOfLines -1)
    $wordArray = $Line.Split("`t")
    $wordArray[($numberOfWords.Words - 1)]
}

Example: Get-Last-Word "C:\Myfolder\MyTextfile.txt"

Upvotes: 2

Shay Levy
Shay Levy

Reputation: 126762

Split the line, remove empty entries if exist, and get the last element:

$content= Get-Content file.txt
$content.Split("`t",[System.StringSplitOptions]::RemoveEmptyEntries)[-1]

Upvotes: 3

Related Questions