0

I would need to extract only last 2 part from the following directory path using shell command

"Android/2.1/Packages/test/debug/"

Expected out put: /test/debug

This path is the dynamic where it would change with different path value as such "Android/2/Pipeline/Packages/test/debug/"

I couldn't find the specific regular expression which can extract the last 2 part even rest of path value keeps change, ie only to get '/test/debug'

Appreciate if any one can help on this

Thanks

umesh
  • 1

2 Answers2

0

I suppose there's many approaches, you could try (replacing pwd with something suitable for your use case):

echo /$(basename $(dirname $(pwd)))/$(basename $(pwd))

or

pwd | awk -F/ '{print "/" $(NF-1) "/" $(NF)}'

And probably countless other ways . . .

Brandon Xavier
  • 2,022
  • 13
  • 15
0

The shell can do this indirectly with variable modifiers %, %%, # and ##. These remove the trailing or leading match for the pattern given. Note that the pattern is a shell glob, not a regular expression.

The following example will print the last two path elements, with or without the optional trailing /

$ in="Android/2/Pipeline/Packages/test/debug/"
$ echo $( t=${in%/} && t=${t%/*/*} && echo ${in##$t} )
/test/debug/
Henk Langeveld
  • 1,314
  • 10
  • 25