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
No related posts.
Leave a Reply
About Me
Tags
Categories
- Algorithms
- Bash
- BlackBerry
- Collaboration
- Command Line
- Cool Tricks
- Easter Eggs
- Ebooks
- Firefox
- Hardware
- Humor
- iPhone
- Linux
- Linux Development
- Linux Kernel
- Networks
- Open Knowledge
- Other
- Productivity
- Programming
- Regular Expressions
- Science
- Security
- Shell Scripts
- Short Posts
- Social Networks
- Thoughts
- Tools
- Vim
- Web Development
- Websites
Popular Posts
Calendar
Archives
- September 2010 (2)
- August 2010 (2)
- July 2010 (5)
- June 2010 (1)
- May 2010 (1)
- April 2010 (3)
- March 2010 (1)
- January 2010 (1)
- December 2009 (2)
- September 2009 (13)
- July 2009 (1)
- June 2009 (6)
- May 2009 (4)
- March 2009 (18)
- February 2009 (10)
- January 2009 (10)
- December 2008 (7)
- November 2008 (8)
- October 2008 (1)
- August 2008 (1)
- July 2008 (1)
- June 2008 (1)
