[英]Searching within column using awk
I am making a contact system through a bashscript. 我正在通过bashscript建立联系系统。 The text file I am inputting contacts in looks like this:
我在其中输入联系人的文本文件如下所示:
Sally May,may@yahoo.com,344-555-4930,Friend
Bill,Bill@yahoo.com,344-555-6543,Co-Worker
In a search option provided I ask (after they pick the column): 在我要求的搜索选项中(他们选择了该列之后):
echo -e"What would you like to search for:\c";;
read search
From here I would like to use the variable $search to go through the FIRST column and give me those lines in a formatted fashion. 在这里,我想使用变量$ search遍历FIRST列,并以格式化的方式给我这些行。 For example:
例如:
If they type in (Bill), then it should return 如果他们输入(Bill),则应返回
Name Email Phone Category
Bill Bill@yahoo.com 344-555-6543 Co-Worker
If they type in (ll), then it should return 如果他们输入(ll),则应返回
Name Email Phone Category
Bill Bill@yahoo.com 344-555-6543 Co-Worker
Sally May may@yahoo.com 344-555-4930 Friend
The line of code I have been working on so far is this: 到目前为止,我一直在研究的代码行是:
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}' ;;
It is giving me an error when I run it. 当我运行它时,它给我一个错误。 Could someone help me fix this!
有人可以帮我解决这个问题! I appreciate it
我很感激
You need to pass variable to awk using -v
option and need to simplify your formatting: 您需要使用
-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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.