0

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

Community
  • 1
  • 1
hzxu
  • 5,753
  • 11
  • 60
  • 95
  • Pretty similar questions from you one [after](http://stackoverflow.com/questions/20415760/script-to-find-all-h-file-and-put-in-specified-folder-with-same-structure) the [other](http://stackoverflow.com/questions/20416524/unix-command-to-copy-all-h-file-with-modified-directory-structure). – devnull Dec 06 '13 at 07:24

1 Answers1

0

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.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • but I need ARBITRARY components, in my case I need the last one, which may not always be the 5th one, so a[5] does not work. – hzxu Dec 06 '13 at 07:03
  • @hzxu, No problem. The last element of an array is numbered "-1". The answer is now updated. – John1024 Dec 06 '13 at 07:07
  • A better way is to use `IFS=/ read -a a <<< "$MYPATH"`. It restricts the change to `IFS` to the `read` command, and it safely handles path components that contain whitespace. – chepner Dec 06 '13 at 14:03
  • Also a heads-up for people still using older versions of `bash`: you may need to use `${a[${#a[@]}-1]}` instead of `${a[-1]}`, as negative subscripts were introduced more recently. – chepner Dec 06 '13 at 14:06