Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regex help needed 1

Status
Not open for further replies.

sbrews

Technical User
Jun 11, 2003
413
0
0
US
I have a variable that has several items in it seperated by a space:

JUNK="item1 item2 item3"
echo $JUNK
item1 item2 item3

Depending on input from the user (via a script), I may need to remove any number of those "items" AND still leave once space between them:

echo $JUNK | *** magical sed command that is eluding me ***
item1 item2 or output could be
item1 item3 or
item2 item3 or
item3 etc. depending what what as entered via the user.

I have been able to match and remove beginning, middle and end leaving 1 space between (if needed), but not all of the above. To restate that in another way - I need to be able to find itemX anywhere in the string and remove it.

Any help would be greatly appreciated.
 
Well, it ain't pretty, but you can do something like this:

Space out the variable that you want to keep. This leaves item2:

Code:
JUNK="item1 item2 item3"
string1="1"
string2=" "
string3="3"

echo $JUNK| sed 's/item['"${string1}"'] //' |sed 's/item['"${string2}"'] //'|sed 's/item['"$
{string3}"']//'

This leaves item1 & item3

Code:
string1=" "
string2="2"
string3=" "

echo $JUNK| sed 's/item['"${string1}"'] //' |sed 's/item['"${string2}"'] //'|sed 's/item['"$
{string3}"']//'

Maybe somebody smarter can come up with a better idea.
 
Perhaps you could use cut...
Code:
$ echo $JUNK
item1 item2 item3
$ echo $JUNK | cut -d ' ' -f 1,2
item1 item2
$ echo $JUNK | cut -d ' ' -f 3
item3
 
Or you can use bash to remove matched strings from a variable, e.g...
Code:
$ JUNK="item1 item2 item3"
$ JUNK=${JUNK//item2/}
$ echo $JUNK
item1 item3
$ JUNK=${JUNK//item3/}
$ echo $JUNK
item1
 
use tr to convert to 1 string per line
grep -v the unwanted string
use tr to convert to strings on one line

Code:
$ JUNK="item1 item2 item3"
$ echo $JUNK
item1 item2 item3
$ ITEM=item2
$ JUNK=$(echo $JUNK|tr ' ' '\n'|grep -v $ITEM|tr '\n' ' ')
$ echo $JUNK
item1 item3

undoubtedly it can be coded in sed also...


HTH,

p5wizard
 
ygor - that works great on newer versions of KSH or bash. unfortunately, I have an older version of KSH and that particular substitution doesnt work - which is a shame as it would have been the ideal solution.

p5wizard - that works perfectly. A star for you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top