Hi
i have a variable var=a_b_c
i want command to find no. of underscores in a variable
Thank you
Hi
i have a variable var=a_b_c
i want command to find no. of underscores in a variable
Thank you
one way:
a=$(echo "$var" | tr -d '[:alpha:]' )
echo ${#a}
Hi can you explain the usages of each command that you used.
What tr -d does?
'[:alpha:]'
??
another way to do it is by using awk:
echo a_b_c | awk -F_ '{print NF-1}'
tr -d list
Delete the characters found in the list from the input stream.
[:alpha:]
A special character class. In this case instead of listing all the letters from a to z and A to Z use this shorthand. A list of these can be found here
Andrew
To count the number of underscores, the most robust solution deletes everything that isn't an underscore.
tr -cd _
Regards,
Alister
Using pure Bash (straight, no chaser) :
var="a_b_c"
count="${var//[^_]}"
echo "${#count}"
2
The discussion in this thread is a continuation of the discussion in the thread No. of underscores in a file name and was already answered there.