Question: Question:
In a shell script, I want to calculate how many ASCII characters are specified by the variable sep from standard input. How can this be achieved?
Answer: Answer:
od | sort | uniq -c
script to create and search histograms:
#!/bin/sh
sep="$1"
pat="($(set -- $(printf %s "$sep" | od -v -An -tx1) && IFS=\| && echo "$*"))\$"
od -v -An -tx1 | xargs -n1 | sort | uniq -c | grep -E "$pat"
Execution example:
$ echo -e " AB...CD\n abcd " | ./script.sh "aB.C
"
2 0a
3 20
3 2e
1 42
1 43
1 61
If you can use od -w1
, you can make the output a little more straightforward (albeit subtle) by doing the following:
od -v -An -tax1 -w1 | xargs -n2 | sort -k2 | uniq -c | grep -E "$pat"
Execution example:
$ echo -e " AB...CD\n abcd " | ./a.sh "aB.C
"
2 nl 0a
3 sp 20
3 . 2e
1 B 42
1 C 43
1 a 61