问题
I've been trying to extract the substring in between parentheses (including parentheses) from:
"WHITE-TAILED TROPIC-BIRD _Phaëthon lepturus_ (Hawaiian name—koae)"
I tried this:
str=$(echo $1 | sed 's/.*\(\([^)]*\)\).*/\1/');
echo $str
What I wanted to get was:
"(Hawaiian name—koae)"
However, I've been getting an error called:
bash: syntax error near unexpected token `('
What do I do wrong?
回答1:
You may use
sed -n 's/.*\(([^()]*)\).*/\1/p'
Here,
-n
- suppresses default line output.*\(([^()]*)\).*
- matches any text, then captures into Group 1 a(
, then 0 or more chars other than(
and)
, then a)
, and then again.*
matches any text to the end of the string/\1/
- replaces the whole match with the contents of Group 1p
- prints the result.
See online demo
In a script called script.sh
:
#!/bin/bash
str=$(echo "$1" | sed -n 's/.*\(([^()]*)\).*/\1/p');
echo "$str"
Called like
bash ./script.sh "WHITE-TAILED TROPIC-BIRD _Phaëthon lepturus_ (Hawaiian name—koae)"
Result: (Hawaiian name—koae)
回答2:
echo "WHITE-TAILED TROPIC-BIRD _Phaëthon lepturus_ (Hawaiian name—koae)" | \
cut -d'_' -f3 | sed s'@^ @@'
If you've got good delimiters, then it is much easier to get parts of lines with cut, than with sed. I only really use sed for replacing characters when I know exactly where they are. For more complex operations, I will usually have to get a piece of text out of the file by inserting carriage returns before and after it with ed, (thus putting it on its' own line, which I can then rip out easily) make the minor changes to it that I want with sed, and then use ed to put it back in.
来源:https://stackoverflow.com/questions/63227813/extract-string-between-parentheses