Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut specific string?

Tags:

powershell

I have a string with different length. I want to cut a specific word in my string. Please help, I am new to PowerShell.

I tried this code, it's still not what I need.

$String = "C:\Users\XX\Documents\Data.txt"
$Cut = $String.Substring(22,0)
$Cut

My expectation is that I can return the word Data.

like image 554
Cheries Avatar asked Mar 21 '26 21:03

Cheries


2 Answers

Assuming the string is always the same format (i.e. a path ending in a filename), then there are quite a few ways to do this, such as using regular expressions. Here is a slightly less conventional method:

# Define the path
$filepath = "C:\Users\XX\Documents\Data.txt"

# Create a dummy fileinfo object
$fileInfo = [System.IO.FileInfo]$filePath

# Get the file name property
$fileInfo.BaseName

Of course, you could do all of this in one step:

([System.IO.FileInfo]"C:\Users\XX\Documents\Data.txt").BaseName
like image 81
boxdog Avatar answered Mar 24 '26 10:03

boxdog


If the path is an existing one, you could use

(Get-Item $String).BaseName

Otherwise

(Split-Path $String -Leaf) -Replace '\.[^\.]*$'