Turning a Multi-Line File Into a CSV File

Date April 10, 2008 by Isaac

Linux has many amazing programs that can be chained together to produce amazing results. Today I needed to turn a multi-line file into a CSV (comma separated) file. In Linux this is super easy:

cat file | tr '\n' ','

Basically, this will turn a file like this:

Line1
Line2
Line3
Line4

Into this:

Line1,Line2,Line3,Line4

2 Responses to “Turning a Multi-Line File Into a CSV File”

  1. Avatarrazak
    1

    hi, appriecate if you could help me,
    i have a very long log file where the contents is like below:

    AAA = 34234
    BBB = somedata
    CCC = somedata2
    DDD = 94383058
    …..

    i need to convert this file to

    34234;somedata;somedata2;94383058

    and I tried to use “tr” command but failed, maybe because the end of line is not \n
    is there any other command can process this log file ?
    really appreciate your help on this
    thanks

    Reply to this comment.
  2. AvatarIsaac
    2
    Author Comment

    hi, appriecate if you could help me,
    i have a very long log file where the contents is like below:

    AAA = 34234
    BBB = somedata
    CCC = somedata2
    DDD = 94383058
    …..

    i need to convert this file to

    34234;somedata;somedata2;94383058

    and I tried to use “tr” command but failed, maybe because the end of line is not \n
    is there any other command can process this log file ?
    really appreciate your help on this
    thanks

    Something like this requires chaining a few commands together. One of the great strengths of Linux is the existence of many “small” commands that can be chained together.

    First, as you indicated, the line ending may need to be adjusted. Try running

    dos2unix <file>

    on the file and then try “tr” again.

    Also, it looks like you want to get rid of all the ‘=’ signs in you log files. Try this:

    cat <file> | sed -r 's/^\w+\s+=\s+//' | tr '\n' ';'

    Reply to this comment.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>