Afficher un message
Vieux 29/05/2007, 21h52   #5
Chris F.A. Johnson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Extracting path components from an absolute path

On 2007-05-29, fia_wrc_fanatic wrote:
> I am trying to write a Bash script that extracts some or all of the
> path components from an absolute path.
> For example, if I have the following absolute path:
>
> INSTALLROOT=/opt/vendor/product/
>
> I need to be able to extract the first path component ("opt" from the
> example above), as well as the remaining string ("vendor/product" from
> the example above).
>
> What's the best way to do this from a Bash script? I have available
> awk, sed, and perl but am not familiar with them to be able to
> accomplish this! In my use cases, the absolute path will never have
> more than 5 or 6 components (i.e. it will not be any deeper than 5 or
> 6 sub-directory levels).


In any POSIX shell (not just bash):

IFS=/
set -f
set -- $INSTALLROOT

The components are now distributed in the positional parameters,
$1 (opt), $2 (vendor), $3 (product) ...

If you just need the last field:

last=${INSTALLROOT##*/}


--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell/>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
  Réponse avec citation
 
Page generated in 0,05205 seconds with 9 queries