如何搜索关键字,然后列出有关此关键字的所有行?

问题描述 投票:1回答:1

我使用标准外壳编写电话簿程序,该程序可以添加,删除和搜索您要查找的联系人。我使用4个变量(姓名,地址,城市和电话号码)存储一位联系人的信息。我将它们逐行放入txt文件中。当我进行搜索时,例如:

Bill
2 wood st.
city
123-4323

当我搜索Bill或wood或4323时,我需要打印所有这4行。sed和awk不允许使用,怎么办?

我使用了只能输出一行的grep。

echo -e "\nEnter name to look up: \c"
read search
grep -i $search book
shell
1个回答
0
投票

这是一个替换grep的awk程序:

#!/usr/bin/bash

read -rp 'Enter a search term: ' search

awk -v search="$search" '
  # read 4 lines as a "record"
  { record = $0; for (i=1; i<=3; i++) { getline; record = record RS $0 } }
  # do the case insensitive pattern match
  tolower(record) ~ tolower(search) { print record }
' book
© www.soinside.com 2019 - 2024. All rights reserved.