How to cut first 3 folders from a string?

For example:

echo "/home/source/Oracle/test" |cut -d'/' -f4 

gives only one folder name, but I need up to the 3rd folder, like below:

echo "/home/test/var/opt" | ... command here ...

should return /home/test/var


Use cut -d "/" -f1-4

ebvjr@Maintenance:~$ echo /home/test/var/opt | cut -d "/" -f1-4
  • Great. One more correct answer. This worked as well. – Muru Jun 13 at 20:00

cut is fine as @ebvjr says, just remember that you need 4 fields because the first is empty.

If you grep then the code is longer but perhaps more intuitive ({3} = the 3rd sub-folder).

grep -Po "(/[^/]+){3}" <<<"/home/test/var/opt"
  • Great. Thanks for your time and helping here. it working – Muru Jun 13 at 19:59

I have done by below awk method


echo "/home/test/var/opt"| awk -F "/" 'OFS="/"{print $1,$2,$3,$4}'



Usually, pathnames are modified through the two utilities basename and dirname, or through parameter substitutions, rather than by line-based text editing utilities.

This is because, technically, pathnames may contain newlines, which would make it difficult to work on the reliably with line-based tools such as cut (or sed or awk etc.)

The example that you have is to get the pathname of the parent directory of /home/test/var/opt. This is best done with

dirname /home/test/var/opt

This would return /home/test/var. This would work even if the given pathname had a / at the end.

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.