Bash Shell Count Number of Characters In a String or Word

How do I count and print particular character (say D or digit 7) in a string or variable under Bash UNIX / Linux shell?

You can use UNIX / Linux command such as sed, grep, wc or bash shell itself to count number of characters in a string or word or shell variable.

grep Command To Count Number of Characters

Use the following syntax to count ‘s’ character in a variable called $x:

x="This is a test"
grep -o "s" <<<"$x" | wc -l

Sample outputs:

3

To match both ‘s’ and ‘S’, enter:

x="This is a test. S"
grep -o "[s|S]" <<<"$x" | wc -l

Sample outputs:

4

Count Number of Characters Using Bash Only

You can use Bash parameter expansion as follows:

x="This is a test"
y="${x//[^s]}"
echo "$y"
echo "${#y}"

To match both ‘s’ and ‘S’, enter:

x="This is a test. S"
y="${x//[^s|S]}"
echo "${#y}"

Please note that all instructions were tested using:

  • Debian GNU/Linux, v6.x
  • GNU grep, v2.6.3
  • GNU bash, v4.1.5

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.