如何使用Bash脚本基于列搜索文本文件

时间:2014-10-16 15:24:53

标签: bash unix awk grep multiple-columns

我正在创建一个bash脚本联系人列表系统,这就是它的打印方式。

=================
Menu
=================

Enter 1 for Insert new contact
Enter 2 for Print current contact list
Enter 3 for Search contact list
Enter 4 for Exit

Enter your selection: 

选择2时,基本上会打印出以下内容:

Name                      Email                     Phone                    

Test                      test@aol.com              102-123-1234             
Data                      data@yahoo.com            345-345-5555             
Sally                     sally@yahoo.com           344-555-4930 

为了显示这个,我使用

$ awk -F, 'BEGIN{printf "%-12s %-15s %-12s\n","Name"," Email"," Phone"} {printf "%-12s %-15s %-12s\n",$1,$2,$3}' contacts.txt            

我遇到第3号选项(搜索联系人列表)时遇到问题。

提示:

Enter in data that you would like to search for: aol

然后背后的代码是:

echo -e "Enter in data that you would like to search for: \c"
    read search
    grep "$search" contacts.txt

打印出来:

Test,test@aol.com,102-123-1234

这是因为文本文件contacts.txt将数据存储在逗号分隔列表中。

我希望搜索结果显示在选项编号为2的列中。所以当" aol"它应该打印出来的搜索:

Name                      Email                     Phone                    

Test                      test@aol.com              102-123-1234  

我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用read和IFS,例如:

echo -e "Enter in data that you would like to search for: \c"
read search
printf "%16s%16s%16s\n\n" Name Email Phone
grep "$search" contacts.txt | while IFS="," read name email phone etc ; do 
  printf "%16s%16s%16s\n" "$name" "$email" "$phone"
done

答案 1 :(得分:0)

awk -v pattern=$search '/Name/{print $0} $0~pattern{print $0}' input

将输出:

Name                      Email                     Phone                    
Test                      test@aol.com              102-123-1234  

它是什么?

  • -v选项会创建一个awk变量pattern,并将其分配给$search
  • /Name/选择标题行
  • $0~pattern与搜索模式匹配

更简单的版本是

awk -v pattern=$search '/Name/; $0~pattern' input

因为print $0是默认操作。