Ikeshima
Ikeshima

Reputation: 19

PowerShell - importing and splitting just one column in a csv file

I have a csv that contains just two columns (called 'newname' and 'name'):

newname, name

newfile1, file1.pdf

newfile2, file2.txt

newfile3, file3.tif

What I would like to do is to import the csv and split column 2 (name) into two columns, like this:

newname, name

newfile1, file1, pdf

newfile2, file2, txt

newfile3, file3, tif

I believe that -Delimiter "." is the way to do this, but I cannot get it to work with the csv import option.

Upvotes: 0

Views: 672

Answers (2)

$csv = @"
newfile1, file1.pdf
newfile2, file2.txt
newfile3, file3.tif
"@ | ConvertFrom-Csv -Header "newFileName", "fileName"
$csv | % {
    .{[PSCustomObject]@{Name = $Args[0][0]; fileName = $Args[0][1]; ext = $Args[0][2]}} (,$_.newFileName + $_.fileName -split "\.(?!.*\.)")
} | Export-Csv d:\tmp\out.txt

just for Biodiversity

Upvotes: 0

Theo
Theo

Reputation: 61218

This is one approach:

Import-Csv -Path 'D:\Test\original.csv' | 
    Select-Object newname, 
                  @{Name = 'name'; Expression = {[IO.Path]::GetFileNameWithoutExtension($_.name)}},
                  @{Name = 'extension'; Expression = {[IO.Path]::GetExtension($_.name).TrimStart(".")}} |
    Export-Csv -Path 'D:\Test\updated.csv' -NoTypeInformation

Result:

newname  name  extension
-------  ----  ---------
newfile1 file1 pdf      
newfile2 file2 txt      
newfile3 file3 tif

Upvotes: 2

Related Questions