Skip to main content

Linux bash string manipulation

Length of a string

${#str}
str="abcdefg"
echo ${#str} #gives output 7

Substring extraction
${str:pos} extracts substring from $str at $pos
str="abcdefg"
echo ${str:2} #gives output cdefg

${str:pos:len} extracts substring from $str at $pos length of $len
str="abcdefg"
echo ${str:2:3} #gives output cde

Substring Removal

${str#substr} removes shortest match of $substr from front of $str
str="abcdefgabcdefg"
echo ${str#a*c} #gives output defgabcdefg

${str##substr} removes longest match of $substr from front of $str
str="abcdefgabcdefg"
echo ${str##a*c} #gives output defg

${str%substr} removes shortest match of $substr from back of $str
str="abcdefgabcdefg"
echo ${str%b*g} #gives output abcdefga

${str%%substr} removes longest match of $substr from back of $str
str="abcdefgabcdefg"
echo ${str%%b*g} #gives output a

Comments

Popular posts from this blog