2017-10-04 16 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があるとします。ですから、script.kshを実行すると出力が次のようになります。

./script.ksh 2 
/singh/is/king/test_1 

コードの説明:Pythonで

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

はい、これは実際に動作します。今、私のbashスキルが開発の初期段階にあるので、正確にあなたが何をしたのか理解する必要があります。 ありがとうございました! –

0

#!/usr/bin/env python3 

import os 
import sys 
print('/'.join(os.getcwd().split('/')[:int(sys.argv[1])+1])) 
関連する問題