Link to home
Start Free TrialLog in
Avatar of phdit
phdit

asked on

CSV file manipulation

Hi All,
I have a csv file wich looks like the below with many thousands of lines.
0021072204,21110016,\\89.1.1.133\SearchByMail\H0517\H0517_CB668_65167\00000018.pdf

I need a Powershell script to go through each line and when ever the first colum character count equals 10 like in the example above swop around colum 1 and 2 so the above example becomes
21110016,0021072204,\\89.1.1.133\SearchByMail\H0517\H0517_CB668_65167\00000018.pdf

Thanks

John Harris
Avatar of oBdA
oBdA

Since you gave absolutely no information about the format of your csv (with or without headers, and if with, the names of the relevant columns), this assumes a csv with header and three columns "Col1", "Col2", "Col3". Adjust to match your actual csv.
If your csv doesn't have a header line, just add
-Header Col1, Col2, Col3
as argument for Import-Csv
Import-Csv -Path C:\Temp\input.csv |
	ForEach-Object {If ($_.Col1.Length -eq 10) {$_.Col1, $_.Col2 = $_.Col2, $_.Col1}; $_} |
	Export-Csv -Path C:\Temp\output.csv -NoTypeInformation

Open in new window

Avatar of phdit

ASKER

Hi thanks for that.
No the csv does not have any headers where would I add

 If your csv doesn't have a header line, just add
-Header Col1, Col2, Col3

I actually got a bit ahead of myself its not a csv file its a text file with , differencing the fields it gets converted to a csv later then loaded into sql.
OK then; this will add and remove the header line:
Import-Csv -Path C:\Temp\input.csv -Header Col1, Col2, Col3 |
	ForEach-Object {If ($_.Col1.Length -eq 10) {$_.Col1, $_.Col2 = $_.Col2, $_.Col1}; $_} |
	ConvertTo-Csv -NoTypeInformation |
	Select-Object -Skip 1 |
	Set-Content -Path | C:\Temp\output.csv

Open in new window

Do you mind the quotes around the fields?
Avatar of phdit

ASKER

PS C:\Users\scanner\Documents> C:\Users\scanner\Documents\hag.ps1
C:\Temp\output.csv : The term 'C:\Temp\output.csv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\scanner\Documents\hag.ps1:5 char:22
+     Set-Content -Path | C:\Temp\output.csv
+                         ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Temp\output.csv:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Im getting this error now running your second script I also DO need the quotes removing too pls.
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of phdit

ASKER

Thanks so much that works a treat.