string manipulation in a script file
I have a string like $(SOMETHING) and want to remove '(' and ')' in a script file. How can I do that? I read that sed command is a filtering utility but don't know how to use it.
|
Sed is a command line editor. Basically it parses a text and do actions based on regular expressions. The 's' command is one of the more used in one-liners: in this case you can substitute every occurrence of '(' and ')' with nothing, e.g.
Code:
string='$(SOMETHING)' Code:
string='$(SOMETHING)' |
If the string is in a bash variable and SOMETHING does not include any "(" or ")" you can do it with two bash parameter expansions like this
Code:
string='$(SOMETHING)' EDIT: Ooops! Colucix already wrote that :) EDIT 2: Now, new, improved! In a single command Code:
string=${string//[()]/} |
Quote:
Code:
string=${string//[()]/} |
Code:
string=$(echo $string | sed 's/[()]//g') Code:
string=${string//[()]/} Thank you all :) |
What's so difficult to understand? It's all explained in the link catkin provided.
${variable} The full form of $variable, necessary in some complex situations. ${variable//foo/bar} Replace all instances of "foo" with "bar" in the variable when expanding it. [] Allows groupings of multiple characters. [ABC] would mean A or B or C. So ${string//[()]/} simply means "replace all instances of ( or ) with nothing when outputting $string, exactly like in the sed statement. |
This should have been like this:
Code:
string=${string/[()]//} |
Quote:
Code:
$ variable="this is a (foo) (bar) string" Code:
echo "${variable/foo/bar}" = echo "$variable | sed 's/foo/bar/'" |
Quote:
|
Quote:
Code:
st="bgerretsberger" |
Quote:
One slash at the front is for a single replacement. Two slashes at the front is for a global replacement. It's the same as the difference between sed "s///" and sed "s///g" Since the opening poster wanted to have all parentheses removed, he'd have to use the two-slash version. In fact, if all you want to do is remove a substring, you don't even need the final slash. The replacement will automatically be "nothing". Code:
$ variable="this is a foo foo foo string" |
Quote:
And why is it replaced with '/'? |
Figure it out.
${variable/[()]//} "variable slash X slash Y". So what is X, and what is Y, in the example above? And what did I just say about the difference between having one slash and two in the first position? |
All times are GMT -5. The time now is 05:53 AM. |