phileas fogg
phileas fogg

Reputation: 1933

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

I need to count the number of control A characters in each line of a file and I'm completely stumped because I don't know what the regex for a control A character would be.

Upvotes: 4

Views: 2881

Answers (5)

ikegami
ikegami

Reputation: 385819

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

perl -nE'say "$.: ", tr/\cA//' file

perl -nE'say "$.: " . ( ()=/\cA/g )' file

Upvotes: 1

mhyfritz
mhyfritz

Reputation: 8522

counting number occurrences of ^A per line (as a perl one-liner):

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

counting total number occurrences of ^A:

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

(edit: fixed typo)

Upvotes: 5

David W.
David W.

Reputation: 107040

Hmm, didn't think of using tr:

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

The s/to/from/g returns the number of times a string is replaced. tr/x/y/ returns the number of characters replaced. In this circumstance, tr/x/y/ will work, but it you're looking for a string and not a single character, you'd run into trouble.

I originally though m/regex/g would work, but it turns out that it only returns a 1 or a 0. Drats.

Upvotes: 1

Jean
Jean

Reputation: 22695

Try this

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

will give

$match=2;

In Gvim you can insert control A by hitting Ctrl+v followed by Ctrl+a

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223023

This seems to work:

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

Or, for a count of each line:

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

Upvotes: 3

Related Questions