简体   繁体   中英

Trim csv cell string with Powershell

I am having trouble using the .Trim() function on a column within a csv file. This csv file only contains one column in the whole table so it should be pretty straight forward (he says).

The data within my csv, Exhibit A ( NOTE: This is all in one field/column, not separate columns ):

Name
C:\Users\kgroome\Documents\NOC\Documentation\Chrome, .pdf
C:\Users\kgroome\Documents\NOC\Documentation\CLI, .docx
C:\Users\kgroome\Documents\NOC\Documentation\DNS, .pdf
C:\Users\kgroome\Documents\NOC\Documentation\Encryption, .pdf
C:\Users\kgroome\Documents\NOC\Documentation\Excel, .xlsx

Ideally I need to trim everything from right to left after the final 5 characters within the string OR split after the , as this would be much more ideal

What I currently have in regards to syntax for splitting after the , is the following:

$data = Import-Csv "C:\Support\Test05.csv"

foreach($line in $data){

    $line.split(',')[5].Trim(); |

    Export-Csv -Path "C:\Support\Test06.csv"

 }

Albeit this isn't my best, I have had previous syntax for both methods however I have scrapped it because it was near useless.

Your help would be extremely appreciated so I can know why I am going wrong!

The fact that you are using a CSV file is a bit of a red herring and I think you want to use replace insread of split:

Get-Content "C:\Support\Test05.csv" | % {
    $_ -replace '\s*,\s*', ','
} | Set-Content "C:\Support\Test06.csv"

I'm only suggesting this to help you understand where your code was not functioning properly. I am still not completely sure what your output is supposed to look like and there are better ways to do this (like with regex)

$file = "c:\temp\text.csv"
$newfile = "c:\temp\text1.csv"

Get-Content $File | ForEach-Object{
    If($_ -match ","){
        $_.Split(",").Trim()[1]
    } Else {
        $_
    }
} | Set-Content $newfile

Output

Name
.pdf
.docx
.pdf
.pdf
.xlsx

Split creates an array from a string based on the delimiter you specify. Splitting on a comma with your sample data will only create an array with two elements. Requesting the sixth element with 5 will simply generate a null.

As for a regex solution this would suffice and generate the same output in the original file.

(Get-Content $File) -replace ".*,\s?" | Set-Content $file

The regex here would grab all characters up until the comma as well as the following space if present. Since the match requires the comma to be there the first row with "Name" is skipped as it does not match.

Maybe this:

gc "C:\Support\Test05.csv" | 
        % { $_.split(',')[-1].trim()} | 
                 set-content "C:\Support\Test06.csv"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM