Input:
ghw//yw/hw///??u
How can i count the slashes("/") using sed?
Input:
ghw//yw/hw///??u
How can i count the slashes("/") using sed?
Don't know how to do it in sed.. but here you have AWK and Perl:
awk -F"/" '{print NF-1}' file
perl -ne '@n=m/\//g;print $#n+1' file
Using sed you still need to count, e.g.:
$ echo ghw//yw/hw///??u | sed s#[^/]##g | wc -L
6
Please explain the perl command.
Match operator (m//) returns all the matched strings as array. So @n contains all the "/"s matched in current line. $#n is index of array's last element, and because Perl starts indexing from 0, we need to add "1" to get total number of elements in array, ergo total number of "/"s in current line.
Please explain the command.
It removes all non-slash characters and then calculates the line length
# printf "%s" "ghw//yw/hw///??u" | sed 's@[^/]@@g' | wc -c
6
if in a variable, use shell expansion
A='ghw//yw/hw///??u'
echo ${A//[^\/]} | wc -L
# ${VAR//<string>} means remove every occurence of <string> in VAR
# the regex [^\/] means anything but not slash (it must be escaped by \)
s="ghw//yw/hw///??u"
s=${s//[^\/]/}
echo ${#s}
And yet another Perl one-liner:
$
$
$ echo "ghw//yw/hw///??u" | perl -lne 'print s|/||g'
6
$
$
tyler_durden
And yet another one with awk:
awk '{print gsub("/",x)}' file
miserable hack to only use sed:
# echo ghw//yw/hw///??u | sed -e 's/\///' -e's#[^/]##g' -e 's/./x\
/g' | sed -n '$='
6
A slightly less miserable version of Tytalus' hack ;):
$ echo ghw//yw/hw///??u | sed 's/\///; y/\//\n/' | sed -n \$=
6
Regards,
Alister