Hello,
I was trying to split a string to characters by perl oneliner.
echo "The quick brown fox jumps over the lazy dog" | perl -e 'split // '
But did not work as with bash script pipe:
echo "The quick brown fox jumps over the lazy dog" | fold -w1 | sort | uniq -ic
8
1 T
1 a
1 b
1 c
1 d
3 e
1 f
1 g
2 h
1 i
1 j
1 k
1 l
1 m
1 n
4 o
1 p
1 q
2 r
1 s
1 t
2 u
1 v
1 w
1 x
1 y
1 z
However, I want ignore the space and case.
1) What did I miss with my perl oneliner?
2) What are the options to ignore the space and case?
3) Want perl oneliner for learning purpose for 2)
Googled for a while, but no example for my exact case. Thanks a lot!
The following code:
echo 'The quick brown fox jumps over the lazy dog' | perl -le 'print join "$/", grep /\S/, split //,<>'
produces:
T
h
e
q
u
i
c
k
b
r
o
w
n
f
o
x
j
u
m
p
s
o
v
e
r
t
h
e
l
a
z
y
d
o
g
Could you clarify what exactly do you mean by "ignore the case"?
I meant to combine upper case and lower case letters. In this example only T and t are redundant. So that letter "t" appears 2 times, not 1 for each. Thanks!
echo 'The quick brown fox jumps over the lazy dog' |
perl -le 'print join "$/", grep /\S/ && !$_{"\L$_"}++, split //, <>
'
If you need the number of occurrences:
echo 'The quick brown fox jumps over the lazy dog' |
perl -le '/\S/ and $l{$_} = ++$cnt{"\L$_"} for split //, <>;
END {
print $cnt{"\L$_"}, " ", $_
for keys %l;
}'
Do you need to preserve the original order?
Thanks roudlov!
There is small bug where "T" and "t" were both counted 2 times. Actually only "t" is needed as "T" should be counted as "t". Anyway, "split //, <>" played the trick for my case. I can pipe the output with sort | unique to get the count:
echo 'The quick brown fox jumps over the lazy dog' | perl -le 'print join "$/", grep /\S/, split //, <>' | tr '[:upper:]' '[:lower:]' | sort | uniq -c
By the way, do you have a good resource to learn perl oneliner? Thanks again!
All in Perl:
echo 'The quick brown fox jumps over the lazy dog' |
perl -le '/\S/ and $cnt{"\L$_"}++ for split //, <>;
END {
print "$cnt{$_} $_"
for sort keys %cnt;
}'
If I understand correctly what you mean by "perl oneliner",
I would suggest Effective Perl Programming: Ways to Write Better, More Idiomatic Perl (2nd Edition).
1 Like