Search code examples
shellvariablesreplace

Remove last two path components of a path in a shell variable


I have a variable var=/usr/local/bin/test/exec

Now i have to remove last 2 path components in the above variable say:

var=/usr/local/bin/

After removing the last 2 strings I have to use this variable 'var' in a shell loop.

I tried:

  var='/usr/local/bin/test/exec'
  echo ${var#$(dirname "$(dirname "$s")")/}
  

Output:

test/exec

I am getting the truncated part as output, but I was expecting the rest of the part, not the truncated part.


Solution

  • OK after some googling i have found the solution for this:

    var1="$(echo $var | cut -d '/' -f-4)"