2

How to generate an output below using bash script/or command:

Desired output:

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

Example input: I have 100 of contacts file for diff. countries.

Contacts.USA

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

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

Contacts.Brazil

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

I'm using unix cmd below but unable to generate the desired output.

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

output of this cmd is showing the result in a row:

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
    Having seen how your first attempt did not do what you wanted, what else have you tried? – DopeGhoti Sep 1 '17 at 21:03
  • I strongly recommend using an actual database. If you have such a huge number of contact files, it will be easier and more robust. – Wildcard Sep 1 '17 at 21:42
  • Linking: unix.stackexchange.com/q/389362/117549 – Jeff Schaller Sep 1 '17 at 23:09
5

awk solution:

Assuming input files contacts.USA and contacts.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 } - capturing line with Name keyword, appending the filename FILENAME to the start of the resulting string

  • if($0~/Address/) print "" - print record separator (newline) after encountering line with Address keyword


The output:

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

Somewhat idiomatic awk version - using "paragraph mode":

$ 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

A similar implementation in perl:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.