Bash shell / Command: strip out arbitrary components in a given path?

164 views Asked by At

Say if I have:

MYPATH=../Library/NetworkUtil/Classes/Headers/network.h

then I want to construct another path AllHeaders/NetworkUtil/network.h

I actually need to get different components out fro the original path, is there a way to do it?

I found in:

Bash: remove first directory component from variable (path of file)

I can something like

${MYPATH#../Library}

to strip out the specified part, but that assumes I know the structure already, what if in my case I need the 3rd and last components in the original path?

Thanks

1

There are 1 answers

4
John1024 On

You can use bash arrays to access individual elements:

$ MYPATH=../Library/NetworkUtil/Classes/Headers/network.h
$ OLD="$IFS"
$ IFS='/' a=($MYPATH)
$ IFS="$OLD"
$ NEWPATH="AllHeaders/${a[2]}/${a[-1]}"
$ echo $NEWPATH
AllHeaders/NetworkUtil/network.h

ADDENDUM: For completeness, another way to make MYPATH into an array is to use bash's pattern substitution: a=(${MYPATH//\// }):

$ MYPATH=../Library/NetworkUtil/Classes/Headers/network.h
$ a=(${MYPATH//\// })
$ NEWPATH="AllHeaders/${a[2]}/${a[-1]}"
$ echo $NEWPATH
AllHeaders/NetworkUtil/network.h

This eliminates the need for messing with IFS but would break badly if MYPATH had spaces, tabs, or CR in it to begin with.