Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell script to convert one-column CSV file

Tags:

powershell

csv

I'm looking for a script, doesn't have to be in PS but must run under Windows, that converts a one column text file like below

abc
def
ghi

into

'abc',
'def',
'ghi'

I'm currently making this change in Excel using =concatenate, but a script would be better.

like image 345
Sean Avatar asked Apr 11 '26 02:04

Sean


2 Answers

Use can use a regular expression to insert characters at beginning and end.

get-content ./myonlinecolumn.txt | foreach {$_ -replace "^","'" -replace "`$","',"} 

Or you could use the format operator -f:

get-content ./myonlinecolumn.txt  | foreach {"'{0}'," -f $_ }

Its a bit more work to remove the last trailing comma, but this also possible

$a = get-content ./myonlinecolumn.txt
get-content ./myonlinecolumn.txt | foreach { if ($_.readcount -lt $a.count) {"'{0}'," -f $_ } else {"'{0}'" -f $_ }}
like image 192
Chad Miller Avatar answered Apr 13 '26 16:04

Chad Miller


My first idea was similar to what Chad already wrote, that is a check on the line number. So I've tried a different solution. Not very nice but I post it too :)

((gc c:\before.txt | % {"'"+$_+"'"} ) -join ",*").split("*") | out-file c:\after.txt
like image 43
Nicola Cossu Avatar answered Apr 13 '26 14:04

Nicola Cossu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!