简体   繁体   中英

Searching within column using awk

I am making a contact system through a 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. For example:

If they type in (Bill), then it should return

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

If they type in (ll), then it should return

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM