Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the filename from a path

I want to extract filename from below path:

D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv

Now I wrote this code to get filename. This working fine as long as the folder level didn't change. But in case the folder level has been changed, this code need to rewrite. I looking a way to make it more flexible such as the code can always extract filename regardless of the folder level.

($outputFile).split('\')[9].substring(0) 
like image 663
user664481 Avatar asked Mar 05 '16 10:03

user664481


People also ask

How do I separate the filename and path in Python?

split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that. In the above example 'file. txt' component of path name is tail and '/home/User/Desktop/' is head.


2 Answers

If you are ok with including the extension this should do what you want.

$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv" $outputFile = Split-Path $outputPath -leaf 
like image 93
Gordon Avatar answered Sep 19 '22 15:09

Gordon


Use .net:

[System.IO.Path]::GetFileName("c:\foo.txt") returns foo.txt. [System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt") returns foo

like image 42
angularsen Avatar answered Sep 21 '22 15:09

angularsen