PDA

View Full Version : Removing a block of text from a variable in a shell script



SoCalChris
November 29th, 2008, 09:13 AM
I have a string that I'm using in a shell script. How could I remove all text from that string that is within a set of parenthesis?

For example, in this code snippet, I would like to remove the parenthesis, and all text within the parenthesis, and return only "I want to keep this ".


myString="I want to keep this (But I want to remove this)"
echo $myString


Thanks

ghostdog74
November 29th, 2008, 09:30 AM
# str="I want to keep this (But I want to remove this)"
# echo ${str%%(*}
I want to keep this

slavik
November 29th, 2008, 09:51 AM
I would do something like:

str="text (is) text (sometimes) ..."
echo $str | sed 's/\(.*\)//g'

ghostdog74
November 29th, 2008, 10:27 AM
I would do something like:

str="text (is) text (sometimes) ..."
echo $str | sed 's/\(.*\)//g'

that won't do. sed doesn't know about non-greediness.

SoCalChris
November 29th, 2008, 10:32 AM
that won't do. sed doesn't know about non-greediness.

Yeah, slavik's code returns

"text ..."

How could I use the example you provided, assuming that there is still text that I want after the closing parenthesis?

Using slavik's example, I would like "text (is) text (sometimes) ..." to return "text text ..."

Thanks for both of your guy's help.

JohnFH
November 29th, 2008, 11:45 AM
Try this:


echo $str | sed 's/([A-Z a-z]*) //g'

ghostdog74
November 29th, 2008, 12:00 PM
assuming no spaces in those brackets, you can go over each word one by one, testing each word for ( or )


var="text (is) text (sometimes) ..."
echo $var |awk '
{
for(i=1;i<=NF;i++){
if($i !~ /[)]/){
print $i
}
}
}
'


other ways include using Perl/Python that uses regexp with non greedy support.

geirha
November 29th, 2008, 01:17 PM
echo "$var" | sed 's/([^)]*)//g'

SoCalChris
December 1st, 2008, 03:35 AM
echo "$var" | sed 's/([^)]*)//g'

Thanks, this worked.

slavik
December 1st, 2008, 05:10 AM
yes it does ...

echo "$var" | sed 's/\(.*?\)//g' #didn't have the '?' before

ghostdog74
December 1st, 2008, 05:55 AM
yes it does ...

echo "$var" | sed 's/\(.*?\)//g' #didn't have the '?' before

can you show your output, as it doesn't look right for me. I don't use sed often, but AFAIK, geirha's solution is the way to go, at least for sed.

slavik
December 1st, 2008, 06:35 AM
can you show your output, as it doesn't look right for me. I don't use sed often, but AFAIK, geirha's solution is the way to go, at least for sed.
i fail at sed...

echo "$var" | perl -pen 's/\(.*?\)//g'

slavik@slavik-laptop:~$ echo "$var" | perl -pne 's/\(.*?\)//g'
this is and more elsewhere