I am trying to use sed to delete a particular item in a list in a text file that is formatted in a particular way. I'll simply illustrate by example; I have ...
ITEMS="$ITEM $ITEM1 $ITEM2 $ITEM3"
And I want to delete $ITEM from the list so this will become ...
ITEMS="$ITEM1 $ITEM2 $ITEM3"
The list could also even just contain $ITEM alone without the numbered $ITEM's, like ...
ITEMS="$ITEM"
And this would become
ITEMS=""
Once $ITEM is deleted out of it of course.
It is not known how many $ITEM's exist in the list while executing this find/delete. The said text file contains other text besides this line, but ITEMS= is unique to the beginning of the lines of the text file, i.e. this is the only line that starts with ITEMS=. So basically, I would like to find the line beginning with ITEMS= and delete the $ITEM element out of it. How could this best be accomplished using sed?
the spaces before and after $ITEM
are really annoying. :)
try this line:
sed -r 's/"\$ITEM /"/; s/\$ITEM //g; s/ ?\$ITEM"/"/' file
test with some example:
kent$ echo 'ITEMS="$ITEM"'|sed -r 's/"\$ITEM /"/; s/\$ITEM //g; s/ ?\$ITEM"/"/'
ITEMS=""
7pLaptop 20:57:44 /home/kent/myCodes/vim/last256
kent$echo 'ITEMS="$ITEM $ITEM1 $ITEM2 $ITEM $ITEM3 $ITEM"'|sed -r 's/"\$ITEM /"/; s/\$ITEM //g; s/ ?\$ITEM"/"/'
ITEMS="$ITEM1 $ITEM2 $ITEM3"
EDIT
for OP's comment, add explanation.
's/"\$ITEM /"/; #step1 check if the first element is $ITEM, do sub
s/\$ITEM //g; #step2 handle the middle elements
s/ ?\$ITEM"/"/' #step3 handle the last element case. also this handles single ("$ITEM") case.
I used 3 steps because OP wants to have same format (single space separated values) after the processing. There maybe simpler/nicer solution for it, I just thought of this way, do the substitution/formating in 3 steps. :(