I wasn't aware that
sed could use a question mark to mean "zero or one instances of preceding character" (appears to be an error in my copy of
Linux in a Nutshell), so I was hoping the
Linux Journal reference would explain the logic. It didn't. (BTW,
here is the link w/o the colon tagged on the end.
) But when I tried the command out it didn't seem to work. And playing around with removing the backslashes (which I thought were wrong) only got me completely confused. So if somebody can give me a coherent explanation of the use of those questions marks and (possibly) backslashes, I would appreciate it. In the meantime, here is a version I understand and I am pretty sure it works:
Code:
PATH=$(echo :$PATH | sed "s@:/path/to/remove@@; s@^:@@")
Explanation: I add a colon before $PATH so that first path element is not special. The
sed command deletes the undesired path along with its preceding colon and then deletes the (remaining) initial colon for the string. The same idea could be applied with a colon added to the end instead, with appropriate changes to the
sed command.
EDIT:
Upon further reflection I realized that if the path element to delete matches part of another path element, the above statement could result in doing something other than what was intended. (I believe the statement from the LJ article also suffers from this.) This problem can be avoided by bracketing the element to delete with colons on both sides:
Code:
PATH=$(echo :$PATH: | sed "s@:/path/to/remove:@:@; s@^:@@; s@:$@@")