I have a space-delimited string of files that may or may not be prefixed with "/" (i.e. their paths are relative to a given root):
mydirs='a /b/c /d/e/f g /h/i'
I need to prefix each file with the root provided by the user. I need a portable way of doing this (It also goes without saying that I prefer speed, so builtins are welcome). So we're all on the same page, by "portable" I mean "portable across different linux shells (sh, bash, ksh, zsh, tsh, csh, etc.)"
Currently, my solution is:
root="my_root" # User-supplied root directory
prefixed_dirs=`echo $mydirs |
tr ' ' '
' | sed 's;^/*;prefix/;' | tr '
' ' '`
which also puts a space at the end of my line, which isn't what I want.
My desired output would be the single line echoed back to me with the files prefixed, like so:
my_root/a my_root/b/c my_root/d/e/f my_root/g my_root/h/i
I've tried searching SO for answers, but I haven't really found what I'm looking for (please point me to a solution if there is one). I know sed operates on new lines by default, so I'm essentially trying to make sed operate on the beginning of substrings (I can't just look for spaces because it will skip a
in the above).
This works, but the syntax is ugly. Is there a cleaner way to do this (again, while maintaining portability)? Perhaps a clean awk
or perl
one-liner (again, must be portable)? Double points for a clean sed one-liner!
Thanks a lot!