[英]Condensing a Bash script to parse a file
我有這個bash腳本,用於粘貼文本文件,我想使其變得更簡單,更短一些,以使其更有效率,有人對我如何做到這一點有任何想法嗎?
$vi
function displayHelp
{
echo "Use '-f' to set the file to be used "
echo "Use '-s' to sort the data bya column"
echo "Use '-m' to output the rows which match this expression"
}
function displayColumn
{
columnnumber="$2"
awk '{print $'$columnnumber'}' $1
}
function displayParameter
{
parameter="$3"
columnnumber="$2"
awk -v s=$3 -v c=$2 '$c ~ s { print $0 }' $1
}
while getopts f:s:m:h opt
do
case "$opt" in
h) displayHelp;;
f) filepath="$OPTARG";;
s) column="$OPTARG"
displayColumn $filepath $column
;;
m) searchParam="$OPTARG"
displayParameter $filepath $column $searchParam
;;
esac
done
在displayColumn()
,您沒有使用-v
變量傳遞,但在displayParameter()
您正在使用。 您應該始終使用-v
而不是嵌入shell變量。
同樣在displayParameter()
您分配了兩個變量,並且從不使用它們。
擴展外殼變量時,應始終引用它們。 當它們單獨出現時,沒有必要在作業的右側引用它們。
如果您要這樣做,則無需強制執行-f
。 如果不提供它(及其必需的參數),您的腳本將嘗試從stdin
讀取(這可能是您想要的)。
沒有強制要求-m
和-s
。 如果沒有這兩個選項,則AWK命令將輸出一條錯誤消息。
通常,必需的參數應作為位置參數處理,選項標志應用於選項(及其參數)。
您的問題可能更適合於代碼審查 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.