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
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop







![Linux Copy File Command [ cp Command Examples ]](http://s13.cyberciti.org/images/shared/rp/3/2.jpg)





{ 7 comments… read them below or add one }
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.
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.
Thank you for your reply with that good link you give.
A=”Ciao Mondo”
echo ${#A}
10
A whitespace is also counted as a character.
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
[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