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:Sample outputs:
x="This is a test"
grep -o "s" <<<"$x" | wc -l
3To match both 's' and 'S', enter:
Sample outputs:
x="This is a test. S"
grep -o "[s|S]" <<<"$x" | wc -l
4
Count Number of Characters Using Bash Only
You can use Bash parameter expansion as follows:To match both 's' and 'S', enter:
x="This is a test"
y="${x//[^s]}"
echo "$y"
echo "${#y}"
Please note that all instructions were tested using:
x="This is a test. S"
y="${x//[^s|S]}"
echo "${#y}"
- Debian GNU/Linux, v6.x
- GNU grep, v2.6.3
- GNU bash, v4.1.5
No comments:
Post a Comment