Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a CSV File Using Grep

Tags:

Lets say I have a csv file like this:

a,b1,12, a,b1,42, d,e1,12, r,12,33, 

I want to use grep to return only only the rows where the third column = 12. So it would return:

a,b1,12, d,e1,12, 

but not:

r,12,33, 

Any ideas for a regular expression that will allow me to do this?

like image 336
David Avatar asked Mar 03 '10 18:03

David


People also ask

How do I grep a file to search?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How do I view the contents of a CSV file?

If you already have Microsoft Excel installed, just double-click a CSV file to open it in Excel. After double-clicking the file, you may see a prompt asking which program you want to open it with. Select Microsoft Excel. If you are already in Microsoft Excel, you can choose File > Open and select the CSV file.

Does grep search line by line?

The GREP command - an overviewBy default, grep displays the matched lines, and it can be used to search for lines of text that match one or more regular expressions, and it outputs only the matched lines.


1 Answers

I'd jump straight to awk to test the value exactly

awk -F, '$3 == 12' file.csv 

This, and any regexp-based solution, assumes that the values of the first two fields do not contain commas

like image 55
glenn jackman Avatar answered Oct 16 '22 02:10

glenn jackman