使用awk在列内搜索

时间:2014-11-06 17:56:14

标签: bash unix awk scripting multiple-columns

我正在通过bashscript建立联系系统。我输入联系人的文本文件如下所示:

Sally May,may@yahoo.com,344-555-4930,Friend
Bill,Bill@yahoo.com,344-555-6543,Co-Worker

在提供的搜索选项中,我问(在他们选择列之后):

echo -e"What would you like to search for:\c";;
read search

从这里开始,我想使用变量$ search来浏览FIRST列并以格式化的方式给我这些行。例如:

如果他们输入(比尔),那么它应该返回

Name                      Email                     Phone             Category         
Bill                      Bill@yahoo.com            344-555-6543      Co-Worker

如果他们输入(ll),那么它应该返回

Name                      Email                     Phone             Category         
Bill                      Bill@yahoo.com            344-555-6543      Co-Worker
Sally May                 may@yahoo.com             344-555-4930      Friend

到目前为止,我一直在研究的代码是:

awk -F, '{ if ($1 ~/$search/) print $0 }' contacts.txt | awk -F, 'BEGIN{printf "%-25s %-25s %-25s %-25s\n","Name","Email","Phone","Category"} {printf "%-25s %-25s %-25s %-25\n",$1,$2,$3,$4}' ;;

我跑的时候给了我一个错误。有人可以帮我解决这个问题!我很感激

2 个答案:

答案 0 :(得分:0)

您需要使用-v选项将变量传递给awk,并且需要简化格式化:

s='ll'
awk -F, -v s="$s" '$0 ~ s{$1=$1; print}' file | column -t
Sally  May             may@yahoo.com  344-555-4930  Friend
Bill   Bill@yahoo.com  344-555-6543   Co-Worker

s='Bill'
awk -F, -v s="$s" '$0 ~ s{$1=$1; print}' file | column -t
Bill   Bill@yahoo.com  344-555-6543   Co-Worker

答案 1 :(得分:0)

read -p "What would you like to search for? :" patt

awk -F, 'BEGIN{printf "%-25s%-25s%-25s%-25s\n","Name","Email","Phone","Category"} $1~/'$patt'/{printf("%-25s%-25s%-25s%-25s\n",$1,$2,$3,$4)}' file