Find the answer to your Linux question:
Results 1 to 6 of 6
Hello , I am using RHEL 5.0 and I have some trouble with a CSV file. What I need to do is to grab all the elements from the 3rd ...
  1. #1
    Just Joined!
    Join Date
    Aug 2010
    Posts
    5

    How to create a script that parses a CSV file

    Hello ,

    I am using RHEL 5.0 and I have some trouble with a CSV file.
    What I need to do is to grab all the elements from the 3rd column and place them each on a new line in a different (new) file.

    For example, if the CSV file is:
    1,2,3,4
    a,b,c,d
    some,may,write,pool

    then the output file should be:
    3
    c
    write

    I tried to threat each line as a string and grab the 3rd element, but for some reason it fail.

    Can you kindly help me out with an example?

    Thanks.

  2. #2
    tpl
    tpl is offline
    Linux User
    Join Date
    Jan 2007
    Location
    cleveland
    Posts
    452
    welcome to the forum

    if the CVS file is called "file" then something like this should work:

    cut -d , -f 3 <file
    the sun is new every day (heraclitus)

  3. #3
    Linux Newbie
    Join Date
    Apr 2010
    Location
    Novosibirsk, Russia
    Posts
    136

    Post

    Within a script, you can use regular expressions, or 'split' function.

    Using split:
    Code:
    my @words = split ",", $csv_line;
    my $needed_word = words[2];
    regexp:
    Code:
    $csv_line =~ /^[^,]*,[^,]*,([^,]*),/;
    $needed_word = $1;

  4. #4
    Linux Newbie theNbomr's Avatar
    Join Date
    May 2007
    Location
    BC Canada
    Posts
    150
    In some cases, you can parse CSV files simply by using tools such as cut. However, these break down as soon as you have fields with embedded commas or quotes. For those cases you are probably best to use some kind of tool built specifically for the purpose of parsing CSV data. You haven't said what programming language you want to use, but my weapon of choice would be Perl, with one of the numerous packages crafted for the purpose, and available from CPAN.

    --- rod.
    Stuff happens. Then stays happened.

  5. #5
    Just Joined!
    Join Date
    Jul 2010
    Posts
    53
    awk -F, '{print $3}'

  6. #6
    Just Joined!
    Join Date
    Aug 2010
    Posts
    5
    Thanks for the advice. I managed to collect data from the CSV file using the tips you provided.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...