2017-04-14 30 views
-1

我是Shell腳本編程的新手。我需要替換文件中的幾個字符串值。它們必須從命令行讀取,shell腳本如下所示。如何將相同的命名參數轉換爲數組

test.sh --old-value yahoo.com --new-value ibibo.io --old-value xxxxxx --new-value yyy --exclude aa bb cc 

現在,我想讀--old值到一個數組, - 新值到其他數組和 - 排除到另一個數組。

我正在嘗試下面的方法。

while [[ $# -gt 1 ]] 
    do 
    key="$1" 

    case $key in 



     --old-value) 
     OLDVALUE="$2" 
     shift # past argument 
     ;; 

     --new-value) 
     NEWVALUE="$2" 
     shift # past argument 
     ;; 

     --exclude) 
     EXCLUDEFILETYPES=("[email protected]") 
     shift 
     ;; 

     *) 
     # unknown option 
    ;; 
esac 
shift # past argument or value 
done 

但是這會將舊值讀入OLDVALUE。我必須將兩個--old值讀入數組。

有人可以幫助如何實現這個用例嗎?

+0

有兩個選項有點冗長,特別是因爲它會出現它們必須成對出現;你有什麼機會把它減少到只有兩個參數的單個選項?例如,'test.sh --replace yahoo.com ibibo.io --replace xxxxx yyy --exclude aa bb cc' – chepner

回答

1
#!/bin/bash 

# declare arrays 
old=(); new=(); exclude=() 

while [[ $# -gt 1 ]]; do 
    key="$1" 
    value="$2" 
    [[ $key == --old-value ]] && old+=("$value") 
    [[ $key == --new-value ]] && new+=("$value") 
    [[ $key == --exclude ]] && shift && exclude+=("[email protected]") 
    shift 2 
done 

# show content of arrays 
declare -p old new exclude 

我假設--exclude aa bb cc是最後一個參數。


實施例:./test.sh --old-value yahoo.com --new-value ibibo.io --old-value xxxxxx --new-value yyy --exclude aa bb cc

輸出:

 
declare -a old='([0]="yahoo.com" [1]="xxxxxx")' 
declare -a new='([0]="ibibo.io" [1]="yyy")' 
declare -a exclude='([0]="aa" [1]="bb" [2]="cc")' 
+0

than you。它爲我工作 – Phani

0

另一變型:

while (($#)); do 
    case "$1" in 
    --old-value) old+=("$2") ;; 
    --new-value) new+=("$2") ;; 
    --exclude) shift; exc=("[email protected]") ; break ;; 
    --*) echo "bad arg" ; exit 1 ;; 
    esac 
    shift;shift 
done 
printf "old: %s\n" "${old[@]}" 
printf "new: %s\n" "${new[@]}" 
printf "exc: %s\n" "${exc[@]}" 

輸出

old: yahoo.com 
old: xxxxxx 
new: ibibo.io 
new: yyy 
exc: aa 
exc: bb 
exc: cc 

當然,這仍然有問題。例如,如果腳本被調用爲

--old-value yahoo.com --new-value --old-value xxxxxx --new-value yyy --exclude aa bb cc 

請注意缺少的新值參數。在這種情況下,結果當然是錯誤的......

old: yahoo.com 
new: --old-value 
exc: 

處理這樣的錯誤情況需要更復雜的狀態處理。

相關問題