Print lines if given column starts with a capital letter

I have a file like this:

ID  A56
DS  /A56
DS  AGE 56

And I’d like to print the whole line only if the second column starts with a capital letter.

Expected output:

ID  A56
DS  AGE 56

What I’ve tried so far:
awk '$2 ~ /[A-Z]/ {print $0}' file
Prints everything: capital letters are found within the second column.

awk '$2 /[A-Z]/' file
Gets a syntax error.

Asked By: dovah


You must use regex ^ to denote start of string:

$ awk '$2 ~ /^[[:upper:]]/' file
ID  A56
DS  AGE 56
Answered By: cuonglm

You could use awk as @cuonglm suggested, or

  1. GNU grep

    grep -P '^[^s]+s+[A-Z]' file 
  2. Perl

    perl -lane 'print if $F[1]=~/^[A-Z]/' file
  3. GNU sed

    sed -rn '/^[^s]+s+[A-Z]/p' file 
  4. shell (assumes a recent version of ksh93, zsh or bash)

    while read -r a b; do 
        [[ $b =~ ^[A-Z] ]] && printf "%s %sn" "$a" "$b"; 
    done < file 
Answered By: terdon
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.