0

I have several projects where I have to use the same command. The projects always are in

/home/[username]/public_html/[prjectname]/

I'd like to run this command from every directory of my projects, so I need to know my project-base. I tried ${path:0:20}, but of cause the string length of the user and projectname varies. I just need to know the first four parts of the path.

**EDIT**

From Stéphane Chazelas' and RudiC's answer:

$ path=/home/[username]/public_html/[prjectname]/abc/xyz
$ echo "${path%"${path#/////}"}"
/home/[username]/public_html/[prjectname]/
No external command needed.

Thanks!

  • You already mention cut. Did you read the manual? – RalfFriedl Oct 23 '18 at 7:15
1

You might want to consider (double) "parameter expansion: Remove matching prefix/suffix pattern":

$ path=/home/[username]/public_html/[prjectname]/abc/xyz
$ echo "${path%"${path#/*/*/*/*/}"}"
/home/[username]/public_html/[prjectname]/

No external command needed.

2

You already mention cut. You just set the delimiter to /. The somewhat unintuitive part is that you need fields 1-5, because the part before the first / is also counted as an (empty) field.

echo /1/2/3/4/5/6/7 | cut -d/ -f1-5

Result is

/1/2/3/4
  • That's exactly what I was looking for! Thanks – Eddy1015 Oct 23 '18 at 7:22
0

Try this,

 find /path/to/dir -mindepth 4 -type d | cut -d"/" -f -5 | sort -u
  • type -d will print only directories.
  • mindepth will print the directories which have minimum 4 subdirectories.
  • -d"/" use / as delimiter to cut
  • -f -5 cut the everything from the fifth column
  • sort -u will print sorted unique folder paths.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.