LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   sed - regular expression (https://www.linuxquestions.org/questions/programming-9/sed-regular-expression-707707/)

Vilmerok 02-26-2009 07:23 AM

sed - regular expression
 
I need to extract substring :

my_string="foo bar(*.*)";

in variable1 should be "foo bar"
in variable2 should be "*.*"

So, everything text beetwen () should be in variable2.

How to create sed regexp for it?

colucix 02-26-2009 07:30 AM

Code:

variable1=$(echo $my_string | sed 's/\(.*\)(.*/\1/')
variable2=$(echo $my_string | sed 's/.*(\(.*\))/\1/')

A must-reading to learn sed programming: http://www.grymoire.com/Unix/Sed.html

pixellany 02-26-2009 07:33 AM

Homework?

colucix 02-26-2009 07:34 AM

Quote:

Originally Posted by pixellany (Post 3458097)
Homework?

Oops... I didn't think about that... sorry!

Vilmerok 02-26-2009 07:55 AM

Quote:

Originally Posted by colucix (Post 3458095)
Code:

variable1=$(echo $my_string | sed 's/\(.*\)(.*/\1/')
variable2=$(echo $my_string | sed 's/.*(\(.*\))/\1/')

A must-reading to learn sed programming: http://www.grymoire.com/Unix/Sed.html

This works, but not correctly:

Code:

c="foo bar(*)"
e=`echo "$c" | sed 's/.*(\(.*\))/\1/'`                                                                                                                      f=`echo "$c" | sed 's/\(.*\)(.*/\1/'`

echo "$e"
echo "$f"

[@my myscript]$ ./script1.sh
*
foo bar

This is perfect!

But if c="foo bar"
[
Code:

@my myscript]$ ./script1.sh
foo bar
foo bar

But should be:
[@my myscript]$ ./script1.sh

foo bar


colucix 02-26-2009 08:44 AM

This should work:
Code:

e=$(echo $c | sed '/(/!d; /(/s/.*(\(.*\)).*/\1/')
it means "for lines not containing parenthesis delete the whole line" while "for lines containing parentheses extract the string within them".


All times are GMT -5. The time now is 07:32 AM.