You may need to find the length of string or size of string variable in your shell script program. Here are the 5 best ways through which you can acheive it.
Above picture may clear you whole story if not please go in details as following.
Consider we have a variable name VAR and it stores a string "Hello" which length is 5.
VAR="Hello"
1) echo : In the bash we can use echo command as following .
2) echo with wc : Second method is echo with wc with -c option as following.
Where -m print the character counts and -c print the byte counts .
3) printf with wc : 3rd method is to use printf with wc as following.
4) echo with awk : 4th method is echo with awk as following.
5) expr : 5th method to use expr as following.
Above picture may clear you whole story if not please go in details as following.
Consider we have a variable name VAR and it stores a string "Hello" which length is 5.
VAR="Hello"
1) echo : In the bash we can use echo command as following .
VAR="Hello"
echo ${#VAR}
5
echo ${#VAR}
5
2) echo with wc : Second method is echo with wc with -c option as following.
VAR="Hello"
echo -n $VAR | wc -m
5
or
echo -n $VAR | wc -c
5
Note:echo -n $VAR | wc -m
5
or
echo -n $VAR | wc -c
5
Where -m print the character counts and -c print the byte counts .
3) printf with wc : 3rd method is to use printf with wc as following.
printf $VAR | wc -c
5
or
printf $VAR | wc -m
5
5
or
printf $VAR | wc -m
5
4) echo with awk : 4th method is echo with awk as following.
echo $VAR | awk '{print length ;}'
5
5
5) expr : 5th method to use expr as following.
expr length $VAR
5
or
expr $VAR : '.*'
5
Watch video in detail 5
or
expr $VAR : '.*'
5
No comments:
Post a Comment