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

2012-01-06

Bash: Saving or Grouping Output from Several Commands

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

You want to capture the output with a redirect, but you’re typing several commands
on one line.
$ pwd; ls; cd ../elsewhere; pwd; ls > /tmp/all.out
The final redirect applies only to the last command, the last ls on that line. All the
other output appears on the screen (i.e., does not get redirected).

Solution:

Use braces { } to group these commands together, then redirection applies to the
output from all commands in the group. For example:

$ { pwd; ls; cd ../elsewhere; pwd; ls; } > /tmp/all.out

There are two very subtle catches here. The braces are actually
reserved words, so they must be surrounded by white space. Also, the
trailing semicolon is required before the closing space.
Alternately, you could use parentheses ( ) to tell bash to run the commands in a subshell,
then redirect the output of the entire subshell’s execution. For example:

$ (pwd; ls; cd ../elsewhere; pwd; ls) > /tmp/all.out