Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Using egrep, how can I print all lines where last names start with K or k?

Jennifer Cowan:548-834-2348:583 Laurel Ave., Kingsville, TX 83745:10/1/35:58900
Lesley Kirstin:408-456-1234:4 Harvard Square, Boston, MA 02133:4/22/62:52600
Jennifer Cowan:548-834-2348:583 Laurel Ave., kingsville, TX 83745:10/1/35:58900
Lesley kirstin:408-456-1234:4 Harvard Square, Boston, MA 02133:4/22/62:52600
William Kopf:846-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
Arthur Putie:923-835-8745:23 Wimp Lane, Kensington, DL 38758:8/31/69:126000
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

A first attempt would be

  grep '^[^ ]*  *[Kk]'

But this assumes that there is always exactly one firstname and no initials.
In this example you can use the -i option and replace [Kk] with just k

It might be better to latch on to the first colon

  grep -i ' k[^:]*:'

If you really want to print just the lastname, and not the whole line, you should consider using awk (or perl)


Update: heres how the first grep expression '^[^ ]* *[Kk]' is constructed

  '     apostrophe delimits a parameter that contains spaces
        and other so-called meta-characters that the shell might alter
  ^     caret means start of line
  [     brackets mark a set of characters, any one of which is to be matched
  ^     inside brackets means negation or 'none of the following'
        so `[^ ]` means "not a space"
  ]     is the end of the set.
  *     means 0,1 or more of the prior character
        so `[^ ]*` means any contiguous group of characters that does not 
        contain a space
  then we have two spaces
  *     means 0,1 or more of the prior character
        so space space * means 1 nor more spaces.
  [Kk]  means `K` or `k`
  [^:]* means 0,1 or more characters that are not a colon
  :     followed by a colon
share|improve this answer
    
wow, the first command works great. But coud please explain in details? Thank you so much. –  Steve Sep 29 '12 at 2:51
    
@Steve: See updated answer. You can find more material in man pages and in tutorials on the web. If the answer is useful, please up-vote. –  RedGrittyBrick Sep 29 '12 at 10:28
    
Thank you RedGrittyBrick. I appreciate your help. –  Steve Oct 2 '12 at 15:01
add comment
perl -aF/:/ -ne 'print if $F[0] =~ /\s[Kk]\S+$/'
  • With -aF/:/, the entire line is split into colon-separated fields;
  • $F[0] is the zeroth field and contains the names;
  • /\s[Kk]\S+$/ matches a space (\s), followed by K or k, followed by any number of non-space characters (\S+) until the end of the field ($).
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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