Nasser Heidari

2012-01-09

Bash: String Manipulations

Filed under: Linux — Nasser Heidari @ 23:39
Tags:

Bash supports a surprising number of string manipulation operations. If you use bash in your daily work, I’m pretty sure you will find these operations many useful and handy.

1. Counting Arguments: ${#}
You need to know with how many parameters the script was invoked. Use the shell built-in variable ${#}.

2. String Length: ${#parameter}
The length in characters of the value of parameter is substituted. If parameter is * or @, the value substituted is the number of positional parameters.

3.1 Shortest Substring Match: ${parameter#word}
Deletes the shortest match of word from front of parameter

3.2 Shortest Substring Match: ${parameter%word}
Deletes the shortest match of word from back of parameter

4.1 Longest Substring Match: ${parameter##word}
Deletes the longest match of word from front of parameter

4.2 Longest Substring Match: ${parameter%%word}
Deletes the Longest match of word from back of parameter

5.1 Substring Replacement: ${parameter/pattern/word}
Replace first match of pattern with string.

5.2 Substring Replacement: ${parameter//pattern/word}
Replace All matches of pattern with word.

6.1 Replace beginning and end: ${parameter/#pattern/word}
If pattern matches front end of parameter, substitute word for pattern.

6.2 Replace end and beginning: ${parameter/%pattern/word}
If pattern matches end end of parameter, substitute word for pattern.

You can find more Information and Examples regarding mentioned operators in following links:
http://tldp.org
http://www.linuxtopia.org
http://linuxgazette.net
http://www.thegeekstuff.com

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: