如果你需要有這個腳本的形式,然後以下可能會幫助你一樣。
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).
}
}
}'
你有沒有考慮過使用AWK OFS? –
行'prints = $(echo {1 .. $ nr})'不會工作!在擴展參數之前進行大括號擴展。清楚地說明你的輸入和期望的輸出 – Inian
我的目的是根據參數創建一個包含諸如「$ 1 $ 2 $ 3」之類的變量,並在awk中插入該變量的內容,以便僅選擇我需要的內容。 –