user829174
user829174

Reputation: 6362

How to crop substring on a text file using powershell

In powershell I am trying to read a file named source.txt which has a content similar to this:

\\14.261.214.1\TEST Path OK\DIQ\V199.32\DOWN\15.7.0.8574

And I'm trying to crop only the suffix version (which is 15.7.0.8574) and to append it a file named destination.txt.

like this:

Version = 15.7.0.8574

I was able to read the file content using Get-Content c:\scripts\source.txt how to I crop and save to destination file

Upvotes: 0

Views: 173

Answers (2)

Loïc MICHEL
Loïc MICHEL

Reputation: 26170

get-content source.txt |Split-Path -Leaf | set-content result.txt

Update for V2 you will have to use a variation :

Split-Path -Leaf -Path (gc .\source.txt)

Upvotes: 1

Oscar Foley
Oscar Foley

Reputation: 7025

You can use regular expressions:

$regex = ‘\b(?:[0-9]{1,3}\.){3}[0-9]{1,5}\b$’
$value = select-string -Path "c:\scripts\source.txt" -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } 
write-host $value

Upvotes: 0

Related Questions