I have an CSV file which holds information in below format -

       V1       V2       V3
   1: ITC 02-01-12  96.4500
   2: ITC 03-01-12  97.5833
   3: ITC 04-01-12  97.0500

The Column 'V1' has many names including 'ITC' also 'A & B', 'XXX 40' etc etc.

Now I want to fetch rows which have pattern like ITC in V1 & date pattern XX in V2 or A & B in V1 & date pattern XX in V2. Match for V1 and V2 should be exact match.

In case if I had only 'ITC', I could use below syntax

grep -w ITC,[0-9][0-9] file.csv

But in the present case, I have 2 items for V1 i.e. ITC and 'A & B'. Any pointer what will be the right grep syntax will be highly appreciated

My CSV file is quite big, running in few GBs, so efficient method to fetch such rows will be helpful

  • 1
    For delimited data, you might want to consider using awk or perl instead – steeldriver Jul 4 at 20:21
  • 1
    The fields from the sample file are not separated by commas, but your grep command is looking for 2 subsequent fields separated by a comma. Anyways, taking your unclear and incomplete description at its word, this should do: grep -E '^(ITC|A & B),[0-9][0-9]-' file. If you have GNU grep, grep -P should be faster. – mosvy Jul 4 at 20:24
  • Thanks mosvy. This is working. However can you further elaborate what do you mean by 'If you have GNU grep, grep -P should be faster.'? How can I use grep -P syntax? – Bogaso Jul 4 at 20:32
  • grep -P will let it use the PCRE engine, which in many cases is faster. The basic syntax is the same as for grep -E (egrep), and you could just change the -E with -P. – mosvy Jul 4 at 20:54
  • With 'grep -P' I am getting no values whereas '-E' is working just fine. I also checked PCRE in my Mac and it is already installed with latest version – Bogaso Jul 5 at 5:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.