Trimming Bash Variables – A Summary

This post should summarize the subject of stripping out bash variables, we already talked about on previous posts

Let’s say we have a bash variable (say x), which stores a string (say “ExExampleStringStr”)

Then we can do the following manipulations:

1.

1
y=${x%Str*}

This will trim out the shortest match of the pattern “Str*” from the end of the string.
Thus, y will have the value “ExExampleString”.

2.

1
y=${x%%Str*}

This will trim out the longest match of the pattern “Str*” from the end of the string.
Thus, y will have the value “ExExample”.
3.

1
y=${x#*Ex}

This will trim out the shortest match of the pattern “*Ex” from the beginning of the string.
Thus, y will have the value “ExampleStringStr”.
4.

1
y=${x##*Ex}

This will trim out the longest match of the pattern “*Ex” from the beginning of the string.
Thus, y will have the value “ampleStringStr”. (since ExEx is the longest match of the pattern *Ex)

So remember:
# or ## = beginning
% or %% = end
## or %% = longest match
# or % = shortest match
* is a wildcard matching “any string” (including the empty string).

These tips are according to @bashcookbook‘s. I recommend following him on twitter for many useful bash tips ;)
Have fun

If you enjoyed this post, make sure you subscribe to my RSS feed!

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

No related posts.

Tags:

Saturday, September 5th, 2009 Bash

Leave a Reply

my email
my photo
Hi,
My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and a BSc. in electrical engineering from The Electrical Engineering school , Technion , Israel.
I'm a Verification Engineer in Mellanox Technologies Ltd.
I love Linux, the Command Line and the OpenSource Community.
I used to write Poems (Arabic) when I was able to find time for this.
September 2009
S M T W T F S
« Jul   Dec »
 12345
6789101112
13141516171819
20212223242526
27282930  
SEO Powered by Platinum SEO from Techblissonline

Twitter links powered by Tweet This v1.7.4, a WordPress plugin for Twitter.