4

I am in this directory:

/home/michal/project/test/my-utils/rel/0.1.0

and I would like to get the relative path to /home/michal/project/ in Linux shell:

../../..

I've tried something with sed but I did not succeeded in creating the regular expression. E.g. one of the attempts:

pwd | sed -e "s/.*project\///g" | sed -e "s/[^\/]+/../g"

Any tips how to do it?

Michal Špondr
  • 1,337
  • 2
  • 21
  • 44
  • Maybe just `sed 's,^/[^/]*/[^/]*/[^/]*,../../..,'`? – Wiktor Stribiżew Nov 07 '18 at 14:08
  • @WiktorStribiżew It does not work in an expected way: $ pwd | sed 's,^/[^/]*/[^/]*/[^/]*,../../..,' ../../../project/test/my-utils/rel/0.1.0 I would like to have a relative path to /home/michal/project/ directory. Something without knowing how many subdirectories I have. – Michal Špondr Nov 07 '18 at 14:12
  • So it's more like "Determine how far I need to climb back up my directory tree until I get to the desired folder, that number is how many `../` I need to concatenate for my answer" – JNevill Nov 07 '18 at 14:16
  • 1
    This seems a little bit like an XY problem; what's wrong with just using the absolute path `/home/michal/project`? You can get that with `${path%%/test/*}`. (I'm assuming you know that `test` is the "root" subdirectory.) – chepner Nov 07 '18 at 14:21
  • Try `awk -F/ '{f=0;for(i=2; i<=NF; i++) {if($i!="project" && f==0) {printf "../"} else {if (f==0) {printf "../";f=1} else {printf $i "/"}}}}' <<< "${PWD}"` – Wiktor Stribiżew Nov 07 '18 at 14:57
  • @kvantour Yes, it could be a duplicate. Funny, I've spent at least 10 minutes trying to find something like that, because this basic question has had to be answered somewhere. – Michal Špondr Nov 08 '18 at 06:46

1 Answers1

10

You can use the command realpath:

realpath --relative-to=${PWD} /home/michal/project/

from the help page:

--relative-to=FILE print the resolved path relative to FILE

oliv
  • 12,690
  • 25
  • 45