で
おかげで、あなたは、次のスクリプトの形でこれを持っている必要があります場合は同じであなたを助けるかもしれません。
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).
}
}
}'
あなたはAWK OFSを使用して考えがありますか? –
'prints = $(echo {1 .. $ nr})'行は決してうまくいかないでしょう!カッコ拡張は、パラメータ拡張の前に行われます。あなたの入力と期待される出力を明確に記述してください – Inian
引数に応じて "$ 1 $ 2 $ 3"のようなものを含む変数を作成し、その変数の内容をawkに挿入して必要なものだけを選択することでした。 –