1

I have a text file like the one below. I want to check the second column and print the count of values which have some special characters in them.

101,aaa,d01
102,*&%,d02 
103,$%&,d03
104,###,d04

I tried with awk:

awk -F, '{if ($2 ~ (/^[$*&%#]+$/) count+1;} END {print count}' sample.txt

but it's not working. Is there any way other than awk to do it?

8
  • Could you also elaborate what were you trying to achieve?
    – devnull
    Apr 11, 2014 at 7:03
  • I have to check whether that column value has special characters and if so i want that count also
    – user64676
    Apr 11, 2014 at 7:15
  • Consider including that information in the question. An example or two would also help.
    – devnull
    Apr 11, 2014 at 7:19
  • 1
    If you want people to be able to help you out, you need to phrase your question better. (1) What exactly are you trying to achieve, (2) Sample input, (3) Expected output, (4) Any attempts that you might have made to solve the problem. Unfortunately, the question in it's current form leaves a lot to imagine for the readers. As such, one would hesitate to answer. Even if one does, chances are that the interpretation would be different from what you expect. Good luck.
    – devnull
    Apr 11, 2014 at 7:27
  • 1
    @user64676 way more information. way more. you've missed all four points in devnull's list.
    – strugee
    Apr 11, 2014 at 8:05

3 Answers 3

1

There are many ways to do this. You don't specify this in your question, but your awk approach is attempting to count those second fields that consist entirely of special characters so that's what my solutions are doing as well. If that's not what you want and instead you want to count the fields that simply contain at least one special character remove the ^ and $ from the match operators.

  1. awk:

    awk -F, '{if($2 ~ /^[$*&%#]+$/) cnt++;} END {print cnt}' sample.txt
    
  2. Perl:

    perl -F, -lane '$cnt++ if $F[1]=~/^[\$*&%#]+$/; END{print $cnt}' sample.txt
    
  3. grep (this one assumes there are always only 3 fields):

    grep -cP ',[\$*&%#]+,' sample.txt 
    
  4. Shell

    count=0;
    while IFS="," read one two three; do 
        [[ -z ${two##[\*&%\$#]*} ]] && let count++; 
    done < sample.txt; 
    echo $count
    
0

How about this

awk -F, '{if ($2 ~ /[^:alnum:]/) l=length($2);print $0" "l}' sample.txt
101,aaa,d01 
102,*&%,d02 3
103,$%&,d03 3
104,###,d04 3

Prints each line the count of "special chars", here chars that are not alnum.

0

As others have mentioned, it's not clear exactly what you want to do, but you can fix the syntax of your approach thus:

awk -F, '$2 ~ /^[$*&%#]+$/ { count++ } END {print count}' sample.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .