1

I have a .csv source file with the below data as an example that has the path of the file to process

Name: files_to_process.csv

FILE_PATH,FILE_NAME  
/fts02/network/inbound/flight_route.txt  
/fts02/network/inbound/flight_text.txt  

I need to create an o.p file using files_to_process.csv as source and create below. I need to additional column to each row except the header. the new column will be the file name coming from absolute path.

required o.p

FILE_PATH,FILE_NAME 
/fts02/network/inbound/flight_route.txt,**flight_route.txt** /fts02/network/inbound/flight_text.txt,**flight_text.txt**

Any help?

1 Answer 1

1

Use the Split-Path cmdlet to obtain just the leaf name from the path:

Import-Csv files_to_process.csv |Select-Object FILE_PATH,@{Name='FILE_NAME';Expression={ $_.FILE_PATH |Split-Path -Leaf }} |Export-Csv o.p -NoTypeInformation

The property selector:

@{Name='FILE_NAME';Expression={ $_.FILE_PATH |Split-Path -Leaf }}

will calculate the new FILE_NAME value as just the file name from the existing FILE_PATH value (eg. flight_route.txt)


As far as I remember, Split-Path was introduced in PowerShell 3.0

If you need this to work with PowerShell 2.0, use the [Path]::GetFileName() method:

Import-Csv files_to_process.csv |Select-Object FILE_PATH,@{Name='FILE_NAME';Expression={ [System.IO.Path]::GetFileName($_.FILE_PATH) }} |Export-Csv o.p -NoTypeInformation
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Its working. I need to delete all the double quotes in the csv file. How can I do it
@rick which version of PowerShell are you doing? It's easy in 6/7, but if you're using PowerShell 5 or earlier, then it's a bit more convoluted :)
6 is the version
@rick Try adding -UseQuotes Never to the Export-Csv command

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.