Awk Bash If-Else问题

时间:2014-01-29 07:00:31

标签: bash if-statement awk

如果找到0条记录,我有一个无法打印错误信息的问题。

这就是我现在所拥有的。

function search_title
{
    awk -F':' -v search="$Title" '$2 ~ search { i++;} END { printf "%d records found\n", i }' test.txt
    awk -F':' -v search="$Title" '$2 ~ search { i++; printf "%s, %s,%s,%s,%s\n", $1, $2, $3, $4, $5 } END {}' test.txt
}

function search_author
{
    awk -F':' -v search="$Author" '$2 ~ search { i++;} END { printf "%d records found\n", i }' test.txt
    awk -F':' -v search="$Author" '$2 ~ search { i++; printf "%s, %s,%s,%s,%s\n", $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 found\n", i }' test.txt
    awk -F':' -v search="$Title" -v search1="$Author" '$1 ~ search && $2 ~ search1 { i++; printf "%s, %s,%s,%s,%s\n", $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

我需要一个if else语句来检查awk打印输出中的计数器是否为0“错误!书本不存在”

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

“错误!书籍不存在” 而不是现在的printf是“0 Record Found”

1 个答案:

答案 0 :(得分:1)

每个函数中不需要2个awk命令:

您可以在一个命令中组合两个awk:

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