Paul L. Snyder on 22 Aug 2009 12:30:25 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] the character least likely to find in a Unix file name


On Fri, 21 Aug 2009, TuskenTower wrote:

> We would like to have a sed script that modifies the PATH in a way
> that follows the principle of least astonishment.

Walt's solution is nice and tidy if you don't mind using Perl.  If you're
wedded to sed, here's a possible solution: before using the environment
variables in the s-command, pass each of them through sed to escape your
desired delimiter.

For example:

------------------------------------------------------------------------------
#!/bin/sh

P=/foo:/bar:/bar/baz
O="/ba"
N="/co/co"

echo $P
P=$(echo $P|sed "s/$(echo $O|sed 's:/:\\/:g')/$(echo $N|sed 's:/:\\/:g')/g")
echo $P
------------------------------------------------------------------------------

Tried this out in zsh's sh emulation, and it seems to work as advertised.
I believe most current sh implementations should support $(...) for command
substitution, but I'll defer to JP on that.  $(...) is more convenient than
`...` as it can be nested without escapes.

Note that the above replaces all occurences of '/ba' that appear in P.  If
you're trying to replace a single occurence of a complete entry in the path
variable, you'll need to be careful that your old string is guaranteed not
to match a substring that appears earlier in the path.  (And, of course,
you won't want to use the 'g' flag on the outer sed.) This could be tricky,
and you might do better to break the path string up by the ':' delimiters
and look at each entry individually.

Paul
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug