2017-10-04 64 views
1

我想從「/ home/user/directory/sub」這樣的路徑中選擇一個受參數影響的部分。如果我將這個腳本稱爲./script 2,它應該返回「/ home/user」。在bash中解析路徑

這裏是我的嘗試:

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但打印和路徑,導致不能正常工作。

在此先感謝

+0

你有沒有考慮過使用AWK OFS? –

+0

行'prints = $(echo {1 .. $ nr})'不會工作!在擴展參數之前進行大括號擴展。清楚地說明你的輸入和期望的輸出 – Inian

+0

我的目的是根據參數創建一個包含諸如「$ 1 $ 2 $ 3」之類的變量,並在awk中插入該變量的內容,以便僅選擇我需要的內容。 –

回答

1

如果你需要有這個腳本的形式,然後以下可能會幫助你一樣。

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。所以當我們運行腳本.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). 
} 
} 
}' 
+0

腳本的參數不應該是要解析的路徑,而是要返回的目錄數量。在我的腳本中,「P」取當前路徑的值。當我將腳本運行爲./script 2時,我希望它從當前路徑移出,比如說「/ home/user/directory/sub」到「/ home/user」。 –

+0

@DragosCazangiu,請你現在查看我的編輯版本,讓我知道這是否有助於你。 – RavinderSingh13

+1

是的,這確實有效。現在我只需要明白你做了什麼,因爲我的技能處於發展的早期階段。 謝謝! –

0

在蟒蛇:

#!/usr/bin/env python3 

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