Add a column to each row using powershell for a text file

Viewed 157

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 Answers

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
Related