简体   繁体   中英

powershell combine column in CSV

I am trying to automate a CSV file that contains lots of rows of data. Here is a sample:

  ==========================
  = ID = Last Name =User ID=
  = 22 =  Smith    = 0077  =
  = 22 =  Smith    = 0078  =
  = 22 =  Smith    = 0079  =
  = 22 =  Jones    = 0081  =

and the list goes on.

What I want to do is Combine Column ID with Column Last Name and put it in a new CSV file using Powershell. I tried the following:

@{n='ID';e={$ .ID + ”-” + $ .Last Name}}

Not much luck with this though.

Any help would be appreciated.

I would first start making the content csv compatiable:

Get-Content file.txt | 
Where-Object {$_ -match '^\s+=\s.+\s+=$'} | 
ForEach-Object { $_ -replace '^\s+=\s*|\s+=$' -replace '\s+=\s+',','} | 
ConvertFrom-Csv -Header ID,LastName,UserID

ID LastName UserID
-- -------- ------
22 Smith    0077  
22 Smith    0078  
22 Smith    0079  
22 Jones    0081

And then use Select-Object to create a new column:

...
ConvertFrom-Csv -Header ID,LastName,UserID | 
Select @{n=’ID’;e={$_.ID + '-' + $_.LastName}},UserID

ID       UserID
--       ------
22-Smith 0077  
22-Smith 0078  
22-Smith 0079  
22-Jones 0081

Your column headers have space in them and that should be the first thing you can fix. But other than that this is my sample emp.csv file, script and then newemp.csv as solution.

id  loginid firstname   lastname
1   abc123  John    patel
2   zxy321  Kohn    smith
3   sdf120  Maun    scott
4   tiy123  Dham    rye
5   k2340   Naam    mason
6   lk10j5  Shaan   kelso
7   303sk   Doug    smith

Script

$objs =@();
$output = Import-csv -Path C:\Scripts\so\emp.csv | ForEach { 
$Object = New-Object PSObject -Property @{            
        Computed  = [String]::Concat($_.id,$_.lastname)
        Firstname = $_.firstname            
    }   
    $objs += $Object;
} 
$objs 
$objs | Export-CSv C:\Scripts\so\newemp.csv

Computed    Firstname
1patel  John
2smith  Kohn
3scott  Maun
4rye    Dham
5mason  Naam
6kelso  Shaan
7smith  Doug

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