Search code examples
unixgrepcut

unix command cut + grep to extract some detailed information


I need to count the lines of a file that contains following information.

  1. The first 2 characters have to be 21
  2. The 54th character needs to be 0 or 6
  3. The 57-58 character need to be greater then 49

I need this in a single command if possible. I tried the following:

cut -c 1-2,54 $filename|grep -e 210 -e 216

This gives me the first 2 conditions. I don't know how to get also the 3rd condition to match. If I do something like this:

cut -c 1-2,54,57-58 $filename|grep -e 210 -e 216

Then I get also something like 22160 that matches the pattern, which is not correct.

How can I accomplish this?


Solution

  • I think you may reach your goal by using awk.

    awk '(substr($0,1,2)==21 && (substr($0,54,1)==0 || substr($0,54,1)==6) && substr($0,57,2)>49 ){count=count+1} END{print count==""?0:count}' Your_file
    

    Brief explanation,

    substr($0,s,l): extract the sub-string of $0 start from s and which length is l