【发布时间】:2023-04-13 17:02:01
【问题描述】:
我在脚本中有以下 AWK 语句:
grep -E $city $DATFILE | awk -F "[\t]+" '($3 >= $minbed) && ($4 >= $minsqft) && ($5 <= $maxprice) && ($6 <= $maxweeks)' $DATFILE | sort -nk5 | less
当我运行脚本时,输出为空白。但是,如果我运行以下命令:
grep -E Toronto listing.dat | awk -F "[\t]+" '($3 >= 2) && ($4 >= 500) && ($5 <= 900000) && ($6 <= 10)' listing.dat | sort -nk4 | less
它按预期输出。
我不知道为什么会这样,我什至替换了脚本中的 awk 语句来回显变量,以确保它们正确传递并且它们是正确的。
这是目前为止的脚本:
#!/bin/bash
DATFILE=listing.dat
if [ -f ${DATFILE} ];
then
echo -n "Are you looking into anywhere in the GTA, or a specific city?: "
read uinput
if [ $uinput == "anywhere" ];
then
echo "You have chosen anywhere"
elif [ $uinput == "specific" ];
then
echo -n "Which city?: "
read city
echo -n "Minimum Number of Bedrooms: "
read minbed
echo -n "Minimum Square Footage (500, 600, etc): "
read minsqft
echo -n "Maximum Price: "
read maxprice
echo -n "Maximum Weeks On Market: "
read maxweeks
echo -n "Sort by (price, sqrft, weeks): "
read sortby
if [ $sortby == "price" ];
then
echo -n "Sort by (asc, desc): "
read ascdesc
if [ $ascdesc == "asc" ];
then
grep -E $city $DATFILE | awk -F "[\t]+" '($3 >= $minbed) && ($4 >= $minsqft) && ($5 <= $maxprice) && ($6 <= $maxweeks)' $DATFILE | sort -nk5 | less
elif [ $ascdesc == "desc" ];
then
grep -E $city $DATFILE | awk -F "[\t]+" '($3 >= $minbed) && ($4 >= $minsqft) && ($5 <= $maxprice) && ($6 <= $maxweeks)' $DATFILE | sort -rnk5 | less
fi
fi
fi
else
echo "${DATFILE} Not found!"
fi
你能帮忙吗?
谢谢
【问题讨论】:
-
gawk或awk?你的例子中都有。 -
您的 awk 脚本用单引号括起来。 Shell 变量在单引号内时不会展开。所以你需要使用 -v 将它们分配给一个 awk 变量。
-
无论如何,不要将 grep 结果通过管道传输到 awk。 awk 本身可以通过正则表达式过滤
-
@JerryJeremiah 你能给我举个例子吗?
-
您将 awk 的分隔符设置为
"[\t]+",这将匹配多个制表符。但是 sort 使用任何空格,因此您可能需要使用 -t 将用于排序的字段分隔符设置为与用于 awk 的值相同的值。