2

I have a text file. Each line record an event and the fields are delimited by '|'. Is it possible using some cmdlet like "get-content event.log | export-csv event.csv" to convert text file to csv file?

xxx(1365)|2016-09-29 06:00:00.0|2016-09-29 06:30:00.0|
bbb(110)|2016-09-29 06:30:00.0|2016-09-29 07:00:00.0|
ccc(5243)|2016-09-29 07:00:00.0|2016-09-29 07:30:00.0|
ddd(1950)|2016-09-29 07:30:00.0|2016-09-29 08:00:00.0|
eee(10)|2016-09-29 08:00:00.0|2016-09-29 09:00:00.0|
fff(464)|2016-09-29 09:00:00.0|2016-09-29 10:00:00.0|
dddd(874)|2016-09-29 10:00:00.0|2016-09-29 11:00:00.0|
ggggg(6)|2016-09-29 11:00:00.0|2016-09-29 12:00:00.0|
kkkk(272)|2016-09-29 12:00:00.0|2016-09-29 12:30:00.0|

2 Answers 2

3

The Import-Csv cmdlet allows you to specify a delimiter

$file = Import-Csv .\event.log -Delimiter '|'

so in your case, it can be as simple as

Import-Csv .\event.log -Delimiter "|" | Export-Csv .\event.csv -NoTypeInformation
Sign up to request clarification or add additional context in comments.

1 Comment

To add to that, if you don't have headers on your text file, you can add them with the -Header parameter, i.e. $file = Import-Csv .\event.log -Delimiter '|' -Header "Name","StartTime","EndTime"
0

If the file isn't too big (under a few megabytes) you could do it with a straight-forward String.Replace operation:

$content = ( $fileName | Get-Content )
$content = $content -replace '|' ','
$content | Out-File $fileName

Or more succinctly:

( $fileName | Get-Content ) -replace '|' ',' | Out-File $fileName

This won't work very well for large files (more than a few megabytes) because the entire file is loaded into memory as a System.String instance, then the Replace operation will then create a new instance (thus doubling the memory requirement).

A faster version might read from the input file line-by-line and perform the -replace operation for each line - or even character-by-character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.