I have a variable that prints a directory tree such as:


I am only interested in the first four values, what would be the best way in bash to print only the first directories separated by backslash, such as:

  • Awk is probably not the best choice here, but: awk 'BEGIN{FS=OFS="/"; }{print $1,$2,$3,$4,$5}' – jasonwryan Aug 15 '16 at 2:59

Using awk:

echo /folder1/folder2/folder3/folder4/folder5/folder6 |\
    awk -F/ -vOFS=/ '{ print $1,$2,$3,$4,$5; }'

OFS = Output Field Separator.

$1 .. $5 are required due to the leading slash counting as 1.

Using cut:

echo /folder1/folder2/folder3/folder4/folder5/folder6 |\
    cut -f -5 -d/

Using sed:

echo /folder1/folder2/folder3/folder4/folder5/folder6 |\
    sed 's:\(\(/[^/]\+\)\{4\}\).*:\1:'
  • 2
    all in favour of cut here :) – tink Aug 15 '16 at 3:05

If there are bash and variable

echo ${var%/${var#/*/*/*/*/}}

Other way

IFS=/ var=($var)
printf '%b/' "${var[@]::5}\n\c"

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.