Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a CSV in a Bash script?

Tags:

bash

shell

csv

I am trying to parse a CSV containing potentially 100k+ lines. Here is the criteria I have:

  1. The index of the identifier
  2. The identifier value

I would like to retrieve all lines in the CSV that have the given value in the given index (delimited by commas).

Any ideas, taking in special consideration for performance?

like image 294
tinkertime Avatar asked Oct 13 '09 13:10

tinkertime


People also ask

What is $() in bash script?

$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.

How do I convert a CSV file to a text file in Linux?

So just in case you are using a text only browser, or need to cut and paste, Lukas's answer is to go into your command line, navigate to the right directory and type the command: “cut -d, -f3 report_source. csv | sed 's/”//g > report_links. txt” (without the quotes).


2 Answers

As an alternative to cut- or awk-based one-liners, you could use the specialized csvtool aka ocaml-csv:

$ csvtool -t ',' col "$index" - < csvfile | grep "$value" 

According to the docs, it handles escaping, quoting, etc.

like image 119
Andrey Vlasovskikh Avatar answered Sep 28 '22 12:09

Andrey Vlasovskikh


See this youtube video: BASH scripting lesson 10 working with CSV files

CSV file:

Bob Brown;Manager;16581;Main Sally Seaforth;Director;4678;HOME 

Bash script:

#!/bin/bash OLDIFS=$IFS IFS=";" while read user job uid location  do      echo -e "$user \     ======================\n\     Role :\t $job\n\     ID :\t $uid\n\     SITE :\t $location\n"  done < $1  IFS=$OLDIFS 

Output:

Bob Brown     ======================     Role :   Manager     ID :     16581     SITE :   Main  Sally Seaforth     ======================     Role :   Director     ID :     4678     SITE :   HOME 
like image 24
FRV Avatar answered Sep 28 '22 12:09

FRV