1

I've been trying to figure out how to find how many values in a column which are not present i.e. has just a "."

For example

car.txt

Car           Colour      mpg          Year
vw_golf         blue       56          2006
vw_polo          red       66          2010
honda_civic    white       .           2007
ford_ka          red       .           2014

So the ones I'm interested in are the honda civic and ford ka as they don't have a number present for the mpg column and I want to find out how many values in the mpg column which doesn't have a value (in this case is 2).

The problem I'm having is the period seems to give errors when I use awk command.

  • 1
    awk '$3 ~ /\./ {count++} END{print count}' file – jasonwryan Nov 19 '17 at 22:02
  • @jasonwryan that should probably be $3 == "." (else it will count decimal mpgs like 66.3 as well) – steeldriver Nov 19 '17 at 22:09
  • @steeldriver good point. – jasonwryan Nov 19 '17 at 22:10
  • @jasonwryan so u mean awk '$3 =="." ' file? – Maurice Nov 19 '17 at 22:13
  • Maurice, if any of the answers solved your problem, please accept it by clicking the checkmark next to it. Thank you! – Jeff Schaller Apr 28 '18 at 11:50
0

Short grep approach:

grep -Ec '^\S+\s+\S+\s+\.\s+' file
2

  • -E - allow extended regular expressions
  • -c - print a count of matching lines
  • \S+ - match non-whitespace character(s), it is a synonym for [^[:space:]]
  • \s+ - match whitespace character(s), it is a synonym for [[:space:]]
0

Another grep method, if your file is strictly formatted to have the mpg start at column 28:

$ grep '...........................\.' input
honda_civic    white       .           2007
ford_ka          red       .           2014

$ grep -c '...........................\.' input
2

That's 28 periods (for "any" character) followed by an escaped period ("a period").

Or with awk, as mentioned in the comments:

$ awk '$3 == "."' input
honda_civic    white       .           2007
ford_ka          red       .           2014

$ awk '$3 == "."' input | wc -l
2

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.