Home > Software engineering >  Get the last occurrence of a character from file path and only get file name without file extension
Get the last occurrence of a character from file path and only get file name without file extension

Time:09-28

Basically, I have split a file path by splitting it by the character slash (""). My code is trying to basically get the file name without the file extension as I need it to perform another operation. However, I want to ensure that this code is dynamic in a sense that even if the file path has a few dots (.) in the file path, it will still retrieve the exact file name of the file path but without the file extension? Basically, I just would want to ensure that I get the last occurrence of the . and the file name with no file extension from the File Path. I have tried using the LastIndexOf but it is not working. Thank to anyone in advance who responds to this post.

P.S. $fileparts is being split by the character slash but I do not know why it is not reflecting on the post

$sql_return_path = C:\Documents\Test\testFileResult.txt

#Get file directory with no file name

$filedirectory = Split-Path -Path $sql_return_path

#Split file path to get file name

$fileparts = ($sql_return_path).Split("\")

$fileobject = 0

foreach($x in $filename) {

    $filename = $fileparts[-1]

    #Test
    $filenamenoextension = $filename.LastIndexOf(".")[0]

    #Official
    #$filenamenoextension = $filename.split(".")[0]
    
    $fileobject  
}

Currently, the output of $filenamenoextension when splitting by dot (".") and getting the index 0 is testFileResult which is just the file name WITHOUT the ".txt" file extension.

CodePudding user response:

You can simply use the GetFileNameWithoutExtension method from the System.IO.Path class Example

[System.IO.Path]::GetFileNameWithoutExtension("..\xyz\abc.de") # ==> "abc"

CodePudding user response:

It is possible to use a System.IO.FileInfo object to get the BaseName and Extension properties.

foreach ($f in Get-ChildItem $dir) {
  $content = New-Object System.IO.FileInfo($f)
  echo $content.BaseName
  echo $content.Extension
}
  • Related