My input variable $dirPath contains directory path. The action is to be able to retrieve the last N values in the directory path, where N is passed through a variable $depth. For a fixed N value (say 2) I'm able to achieve this through

subDir=$(echo $dirPath|awk -F "/" '{n= 2; for (--n; n >= 0; n--){ printf "%s/", $(NF-n)} print ""}')

However if I try to replace 2 in the above command with a variable as n=$depth, the subDir variable is empty. So how can I pass a variable value to the above command?


If you would like to pass a bash variable to awk then all you need is to use awk's -v parameter :

awk -v n=$depth -F "/"...

Since you're using bash, no need for external tools such as awk

#read path constituents into array arr
IFS=/ read -ra arr <<<"$dirPath"
#print the last two
(IFS=/; printf '%s\n' "${arr[*]:(-n)}")

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.