Shell tip


During one of my teaching sessions a student asked me if it was possible to find the number of spaces in a variable.

As with all questions in Linux and UNIX the answer is a simple

Of course that’s possible. In UNIX and Linux everything is possible.

With some sed or awk this can be done within seconds. But I wanted it done completely within the shell, in this case bash.

This is what I came up with

P="John and Paul and Ringo and George where the Beatles"
R=${P//[! ]/}		# Remove everything that is NOT a space
echo ${#R}			# Show the number of characters (spaces) that are left

And this also works in the Korn shell (ksh) and the Z-shell (zsh).

code  linux  sysadm 

See also