Link to home
Start Free TrialLog in
Avatar of SQLM_M
SQLM_MFlag for India

asked on

Split content of a csv file using powershell

Hi,
    I want to split the content of a csv file based on a delimiter. The csv file has three columns. I want to split the content of first column i.e i want to split the text after last  occurence of "\". Please provide me a sample.

Sample:
F:\CDR_FTP\SMS\Archive\20110923\IE3_CS_22_09_2011_23_49_00_016145.cdr 68 68
F:\CDR_FTP\SMS\Archive\20110923\IE3_CS_22_09_2011_23_52_18_016146.cdr 68 68
F:\CDR_FTP\SMS\Archive\20110923\IE3_CS_22_09_2011_23_55_30_016147.cdr 68 68
F:\CDR_FTP\SMS\Archive\20110923\IE3_CS_22_09_2011_23_59_11_016148.cdr 15 69

Expected Output:
IE3_CS_22_09_2011_23_49_00_016145.cdr 68 68
IE3_CS_22_09_2011_23_49_00_016146.cdr 68 68
IE3_CS_22_09_2011_23_49_00_016147.cdr 68 68
IE3_CS_22_09_2011_23_49_00_016148.cdr 15 68
Avatar of nepaluz
nepaluz
Flag of United Kingdom of Great Britain and Northern Ireland image

here goes, remember to change the path to your file path
        Using sr = New FileIO.TextFieldParser("YouPath") With {.Delimiters = {"\"}}
            While Not sr.EndOfData
                Dim line = sr.ReadFields()
                Dim TheResult = line.Last
            End While
        End Using

Open in new window

Sorry .... did not see the powershell .....
ASKER CERTIFIED SOLUTION
Avatar of chrismerritt
chrismerritt

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 SQLM_M

ASKER

Hi,

Thanks for your response, I get the following error when i execute your code.

You cannot call a method on a null-valued expression.
At line:3 char:38
+     $LastSection = ($Line.Path).Split <<<< ("\")[-1]
    + CategoryInfo          : InvalidOperation: (Split:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
Avatar of chrismerritt
chrismerritt

To execute my code the CSV must be formatted exactly the same as I have entered, including the "Path" heading at the top of the list of directories.

$Line.Path is saying saying that for each line of the CSV file, use the value found in the "Path" column.

I have tested the script and it does work, so either it's not linking to the right CSV file location or the CSV file does not contain the data in the same way I have entered it.

You can try stepping through it to make sure that values are set properly, i.e. after executing my code but before closing the window, echo back the value of $CSVFile by simply entering $CSVFile into the prompt and hitting return.

You can do this for any value, powershell will remember what it's assigned to variables in the same window, so for example if you do this:

$a = 10

Then afterwards just put this:

$a

It will echo back to you the value 10.
Avatar of SQLM_M

ASKER

Thanks for your solution..