Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV file editing using PowerShell

Tags:

powershell

csv

I need to do below using PowerShell scripting.

I have the below data in CSV file. I need to append another prefix to the name according to the subject supplied

Name,Subject,Roll,Div
Mark,Agri,3,Div1,
Tom,CS,6,Div3,
Alex,Aero,9,Div6

Suppose i am supplied the subject as Agri, the name should have prefix as P-. So the same CSV file will be saved and have below content

Name,Subject,Roll,Div
P-Mark,Agri,3,Div1,
Tom,CS,6,Div3,
Alex,Aero,9,Div6

Here's what I have so far:

(Import-Csv E:\Test.csv -Delimiter ',') | ForEach-Object{

    if($_.Subject -match "Agri" )
    {
      $_ = "P-" + "$_";

    }
    else
    {
     $_ = "F-" + "$_";

    }

} | Export-Csv E:\Test.csv -Delimiter ',' 
like image 658
usr021986 Avatar asked Dec 27 '13 21:12

usr021986


People also ask

Can CSV files be modified?

A CSV (Comma Separated Values) file is a special type of file that you can create or edit in Excel. Rather than storing information in columns, CSV files store information separated by commas.

How do I edit a file in PowerShell?

The easiest way to edit a text file in PowerShell on your Windows machine is to run the command notepad.exe my_text_file. txt , or simply notepad my_text_file. txt , in your PowerShell terminal to open the text file with the visual editor Notepad.


2 Answers

I wasn't able to pipe this together - might just be ignorance on my part about powershell syntax. I was able to do it with the following using two lines:

($csv = Import-Csv E:\Test.csv -Delimiter ',') | ForEach {
    if ($_.Subject -match "Agri") {
        $_.Name = 'P-' + $_.Name
    } else {
        $_.Name = 'F-' + $_.Name
    }

}
$csv | Export-Csv E:\Test.csv -Delimiter ',' -NoType

Notice:

$_ = "P-" + $_;

Becomes

$_.Name = "P-" + $_.Name;
like image 67
crush Avatar answered Sep 20 '22 23:09

crush


It seems to me the use of paren's in the following clause.

($csv = Import-Csv E:\Test.csv -Delimiter ',')

will assign to $csv the output of Import-Csv PRIOR to the ForEach processing and therefore the ForEach effects are completely lost. Not sure what you purpose is in using those paren's.

like image 23
Greg Avatar answered Sep 19 '22 23:09

Greg