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.

ADVERTISEMENTS

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
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
11 comments… add one
  • Justin Yang Jun 23, 2011 @ 14:56

    Hi,
    Just complete this article and feel it’s helpful to me. However, could you offer us more details about the meaning of the following two lines:
    y=”${x//[^s]}”
    and
    echo “${#y}”
    I don’t know what they mean. Thank you.

    • 🐧 nixCraft Jun 25, 2011 @ 14:01

      Find and replace all occurrences of ‘s’ i.e. when pattern begins with /, all matches of pattern are replaced with ‘s’ and stored to $y:

      y=”${x//[^s]}”

      To find string ($y) length:

      echo “${#y}”

      See HowTo: Use Bash Parameter Substitution Like A Pro for more info.

      • Richard Black Mar 18, 2015 @ 18:02

        Here is the breakdown for y=”${x//[^s]}”

        This assumes that you already understand y=”${x}” and somewhat understand %, %%, # and ##.

        / indicates we will be doing pattern substitution as described in the bash man page.

        The pattern section is “/[^s]”

        This pattern has a leading “/” which means bash will replace all matches of pattern.

        The pattern itself “[^s]” means to match any character that is not an “s”. Look up leading “^” inside of square brackets “[ ]”.

        The string is not included because we want to delete any character that is not an “s”. Because the replace string is empty then the “/” that divides pattern from string is not included.

        Then $y is left with only “s”s because everything else has been deleted. So “${#y}” will give you the total count of characters in $y.

        • prashant singh Sep 30, 2015 @ 11:19

          Hi Richard – Thanks a lot for the excellent explanation ……. as more theory more confusion ….some time :) .Thanks again!!

  • Justin Yang Jun 25, 2011 @ 15:32

    Thank you for your reply with that good link you give.

  • mandela900 Jun 27, 2011 @ 8:22

    A=”Ciao Mondo”
    echo ${#A}
    10

    • 🐧 nixCraft Jun 29, 2011 @ 16:42

      A whitespace is also counted as a character.

    • hitendra Apr 11, 2013 @ 15:44

      thanku

  • Uchmann Jul 14, 2011 @ 8:12

    Thanks for the post
    is it wrong doing it this way.
    1. Use the following syntax to count ‘s’ character in a variable called $x:
    echo “$x” | grep -o “s” | wc -l

    2. To match both ‘s’ and ‘S’, enter:
    echo “$x” | grep -oi “s” | wc -l

  • Adilson Apr 6, 2013 @ 15:20

    [Fedora Linux & Debian Linux]

    hello, thanks for scripts.
    I have a directory with 100 files.
    I wonder which of those 100 files has more than 32 characters in the name.
    can you help me?
    Thanks

    • Jared Jun 4, 2014 @ 15:10

      #!/usr/bin/env bash
      # if $filename more than 32 then
      # @param $1 directory

      dir=$1

      for file in “$(ls $dir)”
      do
      file=”${#file}”
      if [ “$file” -gt “32” ]; then
      echo “Filename is more than 32 chars!”
      else
      echo “Filename is NOT more than 32 chars!”
      fi
      done

      Wrote this on the fly, should work.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.