如果您需要以脚本的形式使用它,那么以下内容可能会对您有所帮助。
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:"/")}}}'
在此处也添加上述解决方案的可读性更好的形式。
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:"/")
}
}
}'
假设我们有以下路径/singh/is/king/test_1/test/test2。因此,当我们运行 script.ksh 时,将会输出以下内容。
./script.ksh 2
/singh/is/king/test_1
代码说明:
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).
}
}
}'