Perl script to count the number of control-A characters in a line in a file

I need to count the number of A control characters in each line of the file, and I'm completely blocked because I don’t know what regular expression for the control will be.

+4
source share
5 answers

counting the number of inputs ^ A per line (as a single-line perl):

perl -ne '{print tr/\cA//, $/}' file 

counting the total number of occurrences ^ A:

 perl -ne '{$c += tr/\cA//}END{print $c, $/}' file 

(edit: typo fixed)

+5
source

It works:

 #!/usr/bin/perl -n s/[^\001]//g; $count += length; END {print "$count\n"} 

Or, to count each row:

 #!/usr/bin/perl -n s/[^\001]//g; print length, "\n"; 
+3
source

try it

 $_ = '^Axyz^Apqr'; $match= tr/^A/^A/; 

will give

 $match=2; 

In Gvim, you can paste control A by pressing Ctrl + v and then Ctrl + a

+1
source

Hmm, I did not think to use tr :

 perl -ne '{print s/\cA//g, $/}' 

s/to/from/g returns the number of replaced string. tr/x/y/ returns the number of characters replaced. In this case, tr/x/y/ will work, but you are looking for a string, not a single character, you will have problems.

Initially, although m/regex/g worked, it turned out that it returns only 1 or 0 . Drats.

+1
source

You are trying to count the occurrences of byte 01. It can be represented in both tr /// and m // in several ways, including \cA and \x01 .

 perl -nE'say "$.: ", tr/\cA//' file perl -nE'say "$.: " . ( ()=/\cA/g )' file 
+1
source

All Articles