Bash can do string operations. LOTS of string operations. This is an introduction to bash string operations for those new to Bash's special tool/feature called "Parameter Expansion", (PE), with a focus on typical string operations. Note Bash's Parameter Expansion, (PE), capability is a lot more powerful than the typical string manipulation calls you may be used to. There are some twists in the road up ahead.

Here is a list of some typical string manipulation functions/subroutines that you may already be familiar with:

This article will cover how to do all of these using the Bash PE and will introduce the more powerful actions available with PE's. Pleasenote there is a BasfFaq about PE's already. That FAQ cover's more of the scope of PE capabilities, where this one instead focuses on string operations.

lets assume we have a string variable named fullpath whose value is "usr/home/JosephBaldwin/Its_only_Rock_and_Roll.mp3"

to perform a basename in bash we use the following PE expression: ${fullpath##*/}

to perform a dirname in bash we use the following PE expression: ${fullpath%/*} ##Print string with its trailing /component removed

to perform a dropext in bash we use the following PE expression: ${fullpath%.*}

to perform a droppre in bash we use the following PE expression: ${fullpath#*.}

to perform a getext in bash we use the following PE expression: ${fullpath##*.}

to perform a strlen in bash we use the following PE expression: ${#fullpath}

to perform a leftstr in bash we use the following PE expression: ${fullpath:0:$2} ## usage leftstr "somestring" count

to perform a rightstr in bash we use the following PE expression: ${fullpath:$(( 0 - $2 ))} ## usage rightstr "somestring" count

to perform a midstr in bash we use the following PE expression: ${fullpath:$2:$3} usage midstr "somestring" StartPos count

to perform a substr in bash we use the following PE expression: ${fullpath//$2/$3} substr "somestring" "target-pattern" "new-string"


CategoryShell