2016-03-25 38 views
1

,我想出了這個能夠接受-q或-a作爲選項,都與參數:的選項和參數shell腳本 - 基於以下解決方案更新

> #!/bin/bash 
> 
> input_file="${1:-/dev/stdin}" 
> 
> while getopts ":qa:" opt; do case $opt in 
> 
>  q) 
>  string="$OPTARG" 
>  echo "org = $string" 
>  grep -v '^>' "$input_file" | grep -x '.\{15,30\}' | sort | uniq -c | awk '{print $2, $1}' | perl -lane ' print ">dme" . $n++ . "_count=$F[1]\n$F[0]" if ($F[1] > 2) '  
>  ;; 
> 
>  a) 
>  string="$OPTARG" 
>  echo "org = $string" 
>  grep -v '^>' "$input_file" | grep -x '.\{15,30\}' | sort | uniq -c | awk '{print $2, $1}' | perl -lane ' print ">dme" . $n++ . "_count=$F[1]\n$F[0]" if ($F[1] > 2) ' 
>  ;; 
> 
>  \?) 
>  echo "Invalid option: -$OPTARG" >&2 
>  exit 1 
>  ;; 
>  :) 
>  echo "Option -$OPTARG requires an argument." >&2 
>  exit 1 
>  ;; esac done 

./script.sh -q "hsa" < test.txt > trial.txt

誠如,我拿出選項-m。目前,我對選項q和m有相同的說明,僅用於測試目的。選擇一個作品併產生期望的結果。選項q不會引發錯誤,但不會產生相同的結果。

此外,我想從命令行提供的參數傳遞給perl指令,即我想dme被替換爲命令行提供的任何內容。有沒有辦法做到這一點?現在,perl行運行良好。

謝謝!

+0

'./help.sh sarbbottam

+0

@sarbbottam:管道和過濾器 - 許多程序在unix-like OS從標準輸入讀取並寫入標準輸出 –

+0

'

回答

0

嘗試使用bash,這是第一個註釋後更改

#!/bin/sh 

#!/bin/bash 

補充:

#!/bin/bash 

input_file="${1:-/dev/stdin}" 

#a and q do not have arguments and are interchangeable, option m accepts a three letter string 
while getopts ":qam:" opt; do 
    case $opt in 
    q) 
     echo "-q was triggered" #, Parameter: $OPTARG" >&2 
     #awk "$input_file" '{print $2, $1}' | perl -lane ' print ">one" . $n++ . "_count=$F[1]\n$F[0]" if ($F[1] > 2) ' > output1.txt 
     ;; 
    a) 
     #perl -lane ' print ">one" . $n++ . "_count=$F[1]\n$F[0]" if ($F[1] > 2) ' < "$input_file" > output1.txt 
     echo "-a was triggered" 
     ;; 
    m) 
     echo "-m was triggered, Parameter: $OPTARG" >&2 
     string="$OPTARG" 
     if [ ${#string} = 3 ]; then 
     echo "string $string has length 3! good" 
     else 
     echo "string $string should be of length 3!" 
     exit 
     fi 
     ;; 
    \?) 
     echo "Invalid option: -$OPTARG" >&2 
     exit 1 
     ;; 
    :) 
     echo "Option -$OPTARG requires an argument." >&2 
     exit 1 
     ;; 
    esac 
done 

檢查,我沒有從原始忘記任何事情碼。據我知道你不能調用帶有>的劇本你的選擇之間,但你可以這樣做:

./script.sh -a -q -m "one" -X < test.html 
-a was triggered 
-q was triggered 
-m was triggered, Parameter: one 
string one has length 3! good 
Invalid option: -X 

注意,X是一個無效的選項。

編輯 Andy G更新了他的問題: 您需要更改getopts。如果需要,請檢查文檔:或:: q和a之後。

while getopts ":q:a:" opt; do 

關於perl問題:你能試試嗎?

perl -lane ' print > "$string" . $n++ . "_count=$F[1]\n$F[0]" if ($F[1] > 2) ' 
+0

返回一個錯誤:無法識別的開關:-q(-h將顯示有效的選項) –

+0

好,[[問題沒有了。我更新了我的答案。注意:你不能這樣做 ./help.sh aless80

+0

謝謝!這幾乎是我正在尋找的結構。 –