In case you need to have this in form of script then following may help you in same.
cat script.ksh
var=$1
PWD=`pwd`
echo "$PWD" | awk -v VAR="$var" -F"/" '{for(i=2;i<=(NF-VAR);i++){if($i){printf("%s%s",i==2?"/"$i:$i,i==(NF-VAR)?RS:"/")}}}'
Adding a better readable form of above solution too here.
cat script.ksh
var=$1
PWD=`pwd`
echo "$PWD" |
awk -v VAR="$var" -F"/" '{
for(i=2;i<=(NF-VAR);i++){
if($i){
printf("%s%s",i==2?"/"$i:$i,i==(NF-VAR)?RS:"/")
}
}
}'
Let's say we have following path /singh/is/king/test_1/test/test2. So when we run the script.ksh following will be the output then.
./script.ksh 2
/singh/is/king/test_1
Explanation of code:
cat script.ksh
var=$1 ##creating a variable named var here which will have very first argument while running the script in it.
PWD=`pwd` ##Storing the current pwd value into variable named PWD here.
echo "$PWD" |
awk -v VAR="$var" -F"/" '{##Printing the value of variable PWD and sending it as a standard input for awk command, in awk command creating variable VAR whose value is bash variable named var value. Then creating the field separator value as /
for(i=2;i<=(NF-VAR);i++){##Now traversing through all the fields where values for it starts from 2 to till value of NF-VAR(where NF is total number of fields value and VAR is value of arguments passed by person to script), incrementing variable i each iteration of for loop.
if($i){ ##Checking if a variable of $i is NOT NULL then perform following.
printf("%s%s",i==2?"/"$i:$i,i==(NF-VAR)?RS:"/") ##Printing 2 types of string here with printf, 1st is value of fields(paths actually) where condition I am checking if i value is 2(means very first path) then print / ahead of it else simply print it, now second condition is if i==(NF-VAR) then print a new line(because it means loop is going to complete now) else print /(to make the path with slashes in them).
}
}
}'
prints=$(echo {1..$nr})would never work! Brace expansion happens before parameter expansion. State your input and expected output clearly