2013-03-19 29 views
1

我开始用这个脚本调用WD:尝试选项添加到这个脚本,不太工作

cat "[email protected]" | tr -cs '[:alpha:]' '\n' | tr '[:upper:]' '[:lower:]' 
| sort | uniq -c | sort -n | awk '{print $2 " " $1}' | sort 

这需要任意数量的文件作为输入并打印的话,像这样的文件中分发:

wd file1 file2 

blue 2 
cat 3 
the 5 
yes 1 

现在我试图给它添加2个选项:s和t。 s使脚本获取一个名为stopwords的输入文件,并在进行分发之前从输入文件中删除这些单词。 t以数字n作为参数并仅输出前n个单词。缺省是全部单词。

所以,到目前为止,我有这个脚本。目前,我的问题是,当我尝试使用-t 10选项时,它告诉我找不到文件10,但它应该是一个数字,而不是文件。而且,当我尝试使用-s选项时,它什么也不做,但不输出任何错误。我知道这个问题不是很具体,但是我会很感激任何有关错误的想法。

#!/bin/bash 

stopwords=FALSE 
stopfile="" 
topwords=0 

while getopts s:t: option 
do 
    case "$option" 
    in 
     s) stopwords=TRUE 
     stopfile="$OPTARG";; 
     t) topwords=$OPTARG;; 
     \?) echo "Usage: wd [-s stopfile] [-t n] inputfile" 
      echo "-s takes words in stopfile and removes them from inputfile" 
      echo "-t means to output only top n words" 
      exit 1;; 
    esac 
done 

if [ "stopwords" = FALSE ] 
then 
    cat "[email protected]" | tr -cs '[:alpha:]' '\n' | tr '[:upper:]' '[:lower:]' 
| sort | uniq -c | sort -nr | head -n $topwords | awk '{print $2 " " $1}' | sort 
else 
    cat "[email protected]" | grep -v -f "$stopfile" | tr -cs '[:alpha:]' '\n' | tr '[:upper:]' '[:lower:]' 
| uniq -c | sort -nr | head -n $topwords | awk '{print $2 " " $1}' | sort 
fi 
+0

'stopwords'在'如果[ “禁用词”= FALSE]'应该是'$ stopwords'? – pynexj 2013-03-19 01:54:08

+0

当你看到'bash'脚本出现问题时,尝试'bash -x /你的/脚本',你可能很容易发现有什么问题。 – pynexj 2013-03-19 02:05:43

回答

2

通常while getopts循环之后,你需要shift $((OPTIND - 1))。以下是我前两个kshbash写了一个例子:

PROGNAME=$0 

function _echo 
{ 
    printf '%s\n' "$*" 
} 

function usage 
{ 
    cat << END 
usage: $PROGNAME [-a] [-b arg] [-h] file... 
END 

    exit $1 
} 

function parseargs 
{ 
    typeset opt v 

    [[ $# = 0 ]] && usage 1 

    while getopts ":ab:h" opt "[email protected]"; do 
     case $opt in 
      a) _echo -$opt ;; 
      b) _echo -$opt $OPTARG ;; 
      h) usage ;; 
      :) _echo "! option -$OPTARG wants an argument" ;; 
      '?') _echo "! unkown option -$OPTARG" ;; 
     esac 
    done 
    shift $((OPTIND - 1)) 

    for v in "[email protected]"; do 
     _echo "$v" 
    done 
} 

parseargs "[email protected]"