How to count the number of characters in a line, except a specific character?
GNU awk solution:
awk -v FPAT='[^N[:space:]]' '{ print NF }' file
FPAT='[^N[:space:]]'
- the pattern defining a field value (any character exceptN
char and whitespace)
The expected output:
1
1
1
0
1
2
2
awk '{ gsub("[ N]",""); print length() }'
assuming that count is needed for each line other than space character and N
$ perl -lne 'print tr/N //c' ip.txt
1
1
1
0
1
2
2
- return value of
tr
is how many characters were replaced c
to complement the set of characters given- Note the use of
-l
option, strips newline character from input line to avoid off-by-one error and also adds newline character for the print statement
A more generic solution
perl -lane 'print scalar grep {$_ ne "N"} @F' ip.txt
-a
option to automatically split input line on white-spaces, saved in@F
arraygrep {$_ ne "N"} @F
returns array of all elements in@F
which doesn't match the stringN
- regex equivalent would be
grep {!/^N$/} @F
- regex equivalent would be
- use of
scalar
will give number of elements of the array