需要一个可以在一行中生成包含所有所需信息的输出的命令/脚本

需要一个可以在一行中生成包含所有所需信息的输出的命令/脚本

如何使用 bash 脚本/或命令生成以下输出:

期望的输出:

contacts.USA | Name:John Due | Gender:Male | Age:21 | Address: Texas    
contacts.USA | Name:Ed Mundo | Gender:Male | Age:41 | Address: California    
contacts.BRAZIL | Name:Tom Paul | Gender:Male | Age:26 | Address: Sau Paulo

输入示例:我有 100 个联系人文件用于比较。国家。

联系方式.美国

Name:John Due 
Gender:Male 
Age:21
Address: Texas

Name:Ed Mundo 
Gender:Male 
Age:41 
Address: California

联系方式.巴西

Name:Tom Paul
Gender:Male 
Age:26 
Address: Sau Paulo

我在下面使用 unix cmd 但无法生成所需的输出。

grep -E 'Name|Gender|Age|Address' contacts.*

该命令的输出连续显示结果:

contacts.USA Name:John Due 
contacts.USA Gender:Male 
contacts.USA Age:21 
contacts.USA Address: Texas
contacts.USA Name:Ed Mundo 
contacts.USA Gender:Male     
contacts.USA Age:41    
contacts.USA Address: California    
contacts.BRAZIL Name:Tom Paul     
contacts.BRAZIL Gender:Male    
contacts.BRAZIL Age:26    
contacts.BRAZIL Address: Sau Paulo

答案1

awk解决方案:

假设输入文件contacts.USAcontacts.BRAZIL.

awk '/Name/{ printf "%s | %s",FILENAME,$0 }
     /Gender|Age|Address/{ printf " | %s",$0; if($0~/Address/) print "" }' contacts.*
  • /Name/{ printf "%s | %s",FILENAME,$0 }- 捕获带有Name关键字的行,将文件名附加FILENAME到结果字符串的开头

  • if($0~/Address/) print ""- 遇到带有Address关键字的行后打印记录分隔符(换行符)


输出:

contacts.BRAZIL | Name:Tom Paul | Gender:Male  | Age:26  | Address: Sau Paulo
contacts.USA | Name:John Due  | Gender:Male  | Age:21 | Address: Texas
contacts.USA | Name:Ed Mundo  | Gender:Male  | Age:41  | Address: California

答案2

有点惯用的 awk 版本 - 使用“段落模式”:

$ awk '{$1=FILENAME OFS $1} 1' RS= FS='\n' OFS=' | ' Contacts.*
Contacts.Brazil | Name:Tom Paul | Gender:Male  | Age:26  | Address: Sau Paulo
Contacts.USA | Name:John Due  | Gender:Male  | Age:21 | Address: Texas
Contacts.USA | Name:Ed Mundo  | Gender:Male  | Age:41  | Address: California

Perl 中的类似实现:

perl -Mfeature=say -F'\n' -00ne 'say join " | ", $ARGV, @F' Contacts.*

相关内容