Hi all
Can anybody suggest me, how to get the count of digits in a word
I tried
WORD=abcd1234
echo $WORD | grep -oE [[:digit:]] | wc -l
4
It works in bash command line, but not in scripts
Hi all
Can anybody suggest me, how to get the count of digits in a word
I tried
WORD=abcd1234
echo $WORD | grep -oE [[:digit:]] | wc -l
4
It works in bash command line, but not in scripts
Could you show us how you use this code in your script? If you want to save it in a variable try something like this:
COUNT=`echo $WORD | grep -oE [[:digit:]] | wc -l`
Let me tell you what exactly I want
I have a word having 8 chrs, something like abc12345 or ab123456
Now, if last five chrs are digits then I wanna do some other operation
I used the code
if [ `echo $WORD | cut -c 4-8 | grep -oE [[:digit:]] | wc -l` -eq 5 ]
then
do this...
bash command line it gives the output, but in script it gives "0" always"
$ cat ./testgrep.ksh
#!/bin/ksh
WORD=abc12345
echo $WORD|grep -qE "[[:digit:]]{5}$"
if [ $? -eq 0 ]; then
echo "Do this with $WORD"
else
echo "Else do this with $WORD"
fi
WORD2=ab123456
echo $WORD2|grep -qE "[[:digit:]]{5}$"
if [ $? -eq 0 ]; then
echo "Do this with $WORD2"
else
echo "Else do this with $WORD2"
fi
WORD3=abc1234
echo $WORD3|grep -qE "[[:digit:]]{5}$"
if [ $? -eq 0 ]; then
echo "Do this with $WORD3"
else
echo "Else do this with $WORD3"
fi
exit 0
$ ./testgrep.ksh
Do this with abc12345
Do this with ab123456
Else do this with abc1234
It seems you're on GNU system, so you probably have bash >= 3 and you could try something like this:
$ WORD=abcd1234
$ [[ $WORD =~ [0-9]{5}$ ]] && echo OK || echo KO
KO
$ WORD=abcd12345
$ [[ $WORD =~ [0-9]{5}$ ]] && echo OK || echo KO
OK
#!/bin/ksh
WORD=abcd1234
[[ $(echo "${WORD}" | awk '{print gsub("[0-9]", "")}') -eq 5 ]] && echo OK || echo KO
Or:
% perl -le'print shift=~/\d{5}$/?"OK":"KO"' abcd1234
KO
% perl -le'print shift=~/\d{5}$/?"OK":"KO"' abcd12345
OK
#!/bin/ksh
WORD=abcd1234
[[ $(expr $WORD : '.*\([0-9]\+\)') -eq 5 ]] && echo OK || echo KO
$ WORD=abcd1234
$ count=${#WORD}
$ echo $count
8
AWESOME Replies!!!
This worked in bash
Also Good Idea...
Thank you...
#! /usr/bin/perl
$str="asf123afsdfjlk1243ljk4356jkl57";
@arr=$str=~m/[0-9]+/g;
print join "|",@arr;
In bash you don't need an external command for that:
WORD=abcd1234
temp=${WORD//[!0-9]/}
echo ${#temp}
Great!!
Thank you!