>String manipulation in bash script

By | November 9, 2010

>Suppose you putted

root#a=hello
Now to get length of string stored in variable a
root#echo ${#a}
result will be 5
To get substring from a string we can specify index in following format
root# a=hello
root# echo ${a:2}
Output will be llo (start from index 2 ,bash use 0 as start position)
root# echo ${a:2:2}
Output will be ll since get from index 2 followed by next 2 character.
To get few get from right side we can use
root#echo ${$a:(-2)}
print ‘lo’ last two character from right side.
SubString Removal
To remove a substring from a string we can use either # or % . Let us understand with an example
root# a=”hello world”
root# echo ${a#hello}
Will print ‘world’ because hello removed from front.
To remove from back of string we can use %, for example
root# echo ${a%world}
Will print ‘hello’
## will be used instead of # if longest substring has to be matched from front.
$$ will be used instead of $ if longest substring has to be matched from back.

SubString Replacement
To replace a substring with another substring / can be used. for example
root#a=”hello world”
root#echo ${a,world,everybody}
Will print ‘hello everybody’
To replace globally is given string use // .

Share itShare on FacebookEmail this to someoneTweet about this on TwitterShare on Google+Share on LinkedInPrint this page

Leave a Reply

Your email address will not be published. Required fields are marked *

Current month ye@r day *