2014-11-06 55 views
0

我正在通過bashscript製作聯繫系統。該文本文件,我是在外觀還是輸入聯繫人是這樣的:使用awk在列內搜索

Sally May,[email protected],344-555-4930,Friend 
Bill,[email protected],344-555-6543,Co-Worker 

在搜索選項提供我問(他們選擇列後):

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

在這裏,我想用變量$ search通過第一列並以格式化的方式給我這些行。例如:

如果他們輸入(草案),那麼它應該返回

Name      Email      Phone    Category   
Bill      [email protected]   344-555-6543  Co-Worker 

如果他們輸入(LL),那麼它應該返回

Name      Email      Phone    Category   
Bill      [email protected]   344-555-6543  Co-Worker 
Sally May     [email protected]    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}' ;; 

當我運行它時,它給了我一個錯誤。有人可以幫我解決這個問題!我很感激

回答

0

您需要通過使用可變-v選項awk和需要簡化您的格式:

s='ll' 
awk -F, -v s="$s" '$0 ~ s{$1=$1; print}' file | column -t 
Sally May    [email protected] 344-555-4930 Friend 
Bill [email protected] 344-555-6543 Co-Worker 

s='Bill' 
awk -F, -v s="$s" '$0 ~ s{$1=$1; print}' file | column -t 
Bill [email protected] 344-555-6543 Co-Worker 
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