在bash中解析路径

在bash中解析路径,bash,parsing,awk,Bash,Parsing,Awk,我试图从/home/user/directory/sub这样的路径中仅选择受参数影响的部分。如果我将脚本称为./script2,它应该返回/home/user 以下是我尝试过的: argument=$1 P=$PWD verif=`echo "$P" | grep -o "/" | wc -l` nr=`expr $verif - $argument + 1|bc` prints=$(echo {1..$nr}) path=`echo $P | awk -F "/" -v f="$p

我试图从/home/user/directory/sub这样的路径中仅选择受参数影响的部分。如果我将脚本称为./script2,它应该返回/home/user

以下是我尝试过的:

argument=$1
P=$PWD

verif=`echo "$P" | grep -o "/" | wc -l`

nr=`expr $verif - $argument + 1|bc`  

prints=$(echo {1..$nr})

path=`echo $P | awk -F "/" -v f="$prints" '{print $f}'`
echo $path
我得到了verif和nr的正确结果,但是打印和生成的路径不起作用


提前感谢

如果您需要以脚本的形式提供此信息,那么以下内容可能会对您有所帮助

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:"/")}}}'
代码说明:

在python中:

#!/usr/bin/env python3

import os
import sys
print('/'.join(os.getcwd().split('/')[:int(sys.argv[1])+1]))

你考虑过使用AWK OFS吗?线条打印=$echo{1..$nr}永远不会起作用!大括号展开发生在参数展开之前。清楚地说明您的输入和预期输出我的目的是创建一个包含$1$2$3之类的变量,具体取决于参数,并在awk中插入该变量的内容,以便只选择我需要的内容。脚本的参数不应该是要解析的路径,而应该是要返回的目录数。在我的脚本中,P取当前路径的值。当我运行脚本(如./script2)时,我希望它从当前路径(如/home/user/directory/sub)转到/home/user。是的,这确实有效。现在我只需要理解你到底做了什么,因为我的bash技能还处于开发的早期阶段。谢谢大家!@DragosCazangiu,你能检查一下我对代码的部分解释,让我知道你是否清楚。非常感谢你的解释。是的,很清楚。谢谢你的努力@德拉戈斯卡桑吉,欢迎您,继续学习,不断分享知识,干杯。
./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).
}
}
}'
#!/usr/bin/env python3

import os
import sys
print('/'.join(os.getcwd().split('/')[:int(sys.argv[1])+1]))