基于下面的解决方案,我想出了这个接受-q或-a作为选项,两者都带有参数:
> #!/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有相同的说明,仅用于测试目的。选项a有效并产生所需的结果。选项q不会抛出错误但不会产生相同的结果。
另外,我希望将命令行提供的参数传递给perl指令,即我希望将 dme 替换为从命令行。有没有办法做到这一点?就像现在一样,perl线运行良好。
谢谢!
答案 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
检查我没有忘记原始代码中的任何内容。据我所知,你不能用&gt;调用脚本在您的选项之间,但您可以这样做:
./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) '