Awk Bash If-Else Issue



我有一个问题,如果找到了0个记录,则无法打印错误消息。

这就是我现在所拥有的。

function search_title
{
    awk -F':' -v search="$Title" '$2 ~ search { i++;} END { printf "%d records foundn", i }' test.txt
    awk -F':' -v search="$Title" '$2 ~ search { i++; printf "%s, %s,%s,%s,%sn", $1, $2, $3, $4, $5 } END {}' test.txt
}
function search_author
{
    awk -F':' -v search="$Author" '$2 ~ search { i++;} END { printf "%d records foundn", i }' test.txt
    awk -F':' -v search="$Author" '$2 ~ search { i++; printf "%s, %s,%s,%s,%sn", $1, $2, $3, $4, $5 } END {}' test.txt
}
function search_both
{
    awk -F':' -v search="$Title" -v search1="$Author" '$1 ~ search && $2 ~ search1 { i++;} END { printf "%d records foundn", i }' test.txt
    awk -F':' -v search="$Title" -v search1="$Author" '$1 ~ search && $2 ~ search1 { i++; printf "%s, %s,%s,%s,%sn", $1, $2, $3, $4, $5 } END {}' test.txt
}
read -p $'Title: ' Title
read -p $'Author: ' Author
if [ "$Title" == "" ];
then
search_author
elif [ "$Author" == "" ];
then
search_title
else
search_both
fi

我需要一个如果其他语句来检查计数器是否在尴尬中打印出"错误!书不存在"

例如,标题输入为daft作者输入为linken(两个值都不在test.txt中)

"错误!书不存在"而不是现在的printf是"找到0记录"

您在每个功能中不需要2个尴尬命令:

您可以将两个尴尬结合在一个命令中:

awk -F':' -v search="$Title" -v search1="$Author" '$1 ~ search && $2 ~ search1 {
         i++;
         printf "%s, %s,%s,%s,%sn", $1, $2, $3, $4, $5;
      }
      END {
          if (!i)
             print "Error! Book does not exists!";
          else 
             printf "%d records foundn", i;
      }' test.txt

相关内容

  • 没有找到相关文章

最新更新