0

I have a csv file with two columns and multiple rows, which has the information of files with folder location and its corresponding size, like below

"Folder_Path","Size"
"C:\MSSQL\DATA\UsersData\FTP.txt","21345"
"C:\MSSQL\DATA\UsersData\Norman\abc.csv","78956"
"C:\MSSQL\DATA\UsersData\Market_Database\123.bak","1234456"

What i want do is remove the "C:\MSSQL\DATA\" part from every row in the csv and keep the rest of the folder path after starting from UsersData and all other data intact as this info is repetitive. So my csv should like this below.

"Folder_Path","Size"
"UsersData\FTP.txt","21345"
"UsersData\Norman\abc.csv","78956"
"UsersData\Market_Database\123.bak","1234456"

What i am running is as below

Import-Csv ".\abc.csv" |
    Select-Object -Property @{n='Folder_Path';e={$_.'Folder_Path'.Split('C:\MSSQL\DATA\*')[0]}}, * |
    Export-Csv '.\output.csv' -NTI

Any help is appreciated!

8
  • SO isn't a code writing service. You're more likely to get help if you post your own attempt(s) first. Commented Jan 28, 2019 at 11:22
  • @boxdog Sure, Edited and added my script. Commented Jan 28, 2019 at 11:28
  • why do you have a 2-hours-younger repeat of this @ Need to remove one constant portion from rows in a csv using powershell - Stack Overflow — stackoverflow.com/questions/54403415/… Commented Jan 28, 2019 at 14:08
  • Not getting a proper solution to my query Commented Jan 28, 2019 at 14:24
  • Why not a simple text replace in the file? Could do that even in any text editor. Commented Jan 28, 2019 at 14:24

2 Answers 2

1

Seems like a job for a simple string replace:

Get-Content "abc.csv" | foreach { $_.replace("C:\MSSQL\DATA\", "") | Set-Content "output.csv"

or:

[System.IO.File]::WriteAllText("output.csv", [System.IO.File]::ReadAllText("abc.csv" ).Replace("C:\MSSQL\DATA\", ""))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much Sir. This is exactly what i needed. Works like a charm!
0

This should work:

Import-Csv ".\abc.csv" |
    Select-Object -Property @{n='Folder_Path';e={$_.'Folder_Path' -replace '^.*\\(.*\\.*)$', '$1'}}, Size |
        Export-Csv '.\output.csv' -NoTypeInformation

2 Comments

This one is working, but what this is doing is keeping one folder name just before the file name, but this is not giving me the output that i need, cuz there are a lot of subfolders too in this folder whose info i want to retain. Can there a way in which i can just remove the "C:\MSSQL\DATA\" portion only?
"this is not giving me the output that i need" Possibly not, but it is giving the output you asked for. Your question/example wasn't clear that part to be left was variable.

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.