How do I do string manipulations in bash?

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: much of this material is in FAQ #73. It is being presented here with an approach inteneded to make it more accessable and more easily learned by people who have not had a lot of exposure to Bash.)

Note Bash's 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:

Two that you haven't heard of but would want to use all the time when scripting on *NIX:

This article will cover how to do all of these using the Bash and will introduce the more powerful actions available with Bash's PE's. Please note there is a BashFaq about PE's already. FAQ #73 covers a larger scope of PE capabilities, where this one focuses on string operations.

Lest say we have a bash variable named fullpath that contains "/usr/home/JosephBaldwin/Its_only_Rock_and_Roll.mp3"

Naturally in scripting we would want to manipulate cerain pieces of the path, like just the file name,

For a basename we use the PE expression: ${fullpath##*/} which returns "Its_only_Rock_and_Roll.mp3".

To find the dirname we use the PE expression: ${fullpath%/*} which produces "/usr/home/JosephBaldwin".

To drop the filename extesnion, we use the PE expression: ${fullpath%.*} giving out "/usr/home/JosephBaldwin/Its_only_Rock_and_Roll"

To get the filename's extension we use the PE expression: ${fullpath##*.} generating only "mp3".

To find the strlen the PE expression: ${#fullpath} finds it and its 49.

To get a leftstr, the PE expression: ${fullpath:0:20} grabs the first 20 chars of fullpath to make "usr/home/JosephBaldw".usr/home/JosephBaldwin/Its_only_Roll_and_Roll.mp3

To perform a rightstr in bash we use the following PE expression: ${fullpath:$(( 0 - 20 ))} which gets the last 20 chars, "ly_Rock_and_Roll.mp3".

To perform a midstr in bash we use the following PE expression: ${fullpath:10:20} making "osephBaldwin/Its_onl"

To perform a substr in bash we use the following PE expression: ${fullpath//Rock/Roll} rolling it into "usr/home/JosephBaldwin/Its_only_Roll_and_Roll.mp3".

Why aren't the PE things named more nicely

Can't I just have these a regular functions with nice names?

not totally generalizable

What can I do with PE's that I couldn't do with the string functions above?


CategoryShell