Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
1  
You might also want to check out SwissKnife. –  terdon Jul 25 at 11:57
    
You just needed to add the hat awk '$2~/^[A-Z]/' file –  Jidder Jul 25 at 12:41

2 Answers 2

up vote 5 down vote accepted

You could use awk as @Gnouc 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 %s\n" "$a" "$b"; 
    done < file 
    
share|improve this answer
    
That assumes GNU grep, GNU sed and for the last one, recent versions of ksh93 zsh or bash and that the file doesn't contain backslash characters. Except for the perl one what [A-Z] matches depends on the locale and doesn't make much sense except in the C locale. –  Stéphane Chazelas Jul 25 at 11:49
    
@StéphaneChazelas so -P is a GNU extension? OK. Why does the [A-Z] not make sense? Presumably, the OP would want whatever is defined as a capital letter in their locale right? I added -r for the backslashes. –  terdon Jul 25 at 11:56
1  
backslashes still an issue with Unix-conformant echos. Yes -P is a GNU extension though it's found as well in some BSDs that have forked or rewritten their GNU grep. See there for [A-Z]. Also note that \s is [[:space:]], not [[:blank:]]. –  Stéphane Chazelas Jul 25 at 12:03
    
@StéphaneChazelas I see, thanks. I switched to printf then, just in case. –  terdon Jul 25 at 12:09

You must use regex ^ to denote start of string:

$ awk '$2 ~ /^[[:upper:]]/' file
ID  A56
DS  AGE 56
share|improve this answer

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.