Aleks Ignjatovic
Aleks Ignjatovic

Reputation: 11

AWK help - multi-line output with repeated variables

I have a file with groups of information split up in vertical lines.

group_name  
email1  
email2  
email3

group_name2  
email1  
email2  

group_name3  
email1

etc....

I need help to get it to output to a file in this format:

group_name email1  
group_name email2  
group_name email3  
group_name2 email1  
group_name2 email2   
group_name3 email1

etc...

currently I am running this command:

$ awk 'BEGIN{FS="\n"; RS=""} {print $1,$2}' output.txt > output2.txt  

but the output obviously isn't what I'm looking for as it only looks at the group_name and first email line, then ignores the next few (if they exist) and moves on to the next group.

How do I get this to loop through all lines until there are none, then move to the next group?

Thank you!

Upvotes: 1

Views: 46

Answers (1)

dawg
dawg

Reputation: 103844

You can use awk in paragraph mode and do:

$ echo "group_name
email1
email2
email3

group_name2
email1
email2

group_name3
email1

" | awk -v RS= '{for (i=2;i<=NF;i++) {printf "%s ", $i;} print ""}'

Prints:

group_name email1 email2 email3 
group_name2 email1 email2 
group_name3 email1 

Or, your format:

echo "group_name
email1
email2
email3

group_name2
email1
email2

group_name3
email1

" | awk -v RS= '{for (i=2;i<=NF;i++) {printf "%s %s\n", $1, $i;}}'

Prints:

group_name email1
group_name email2
group_name email3
group_name2 email1
group_name2 email2
group_name3 email1

Then just redirect stdout to the desired output file:

$ awk -v RS= '{for (i=2;i<=NF;i++) {printf "%s %s\n", $1, $i;}}' in_file >out_file

(If there is a possibility of horizontal spaces in the group name or email names, add awk -v RS= -v FS=$'\n' '...' so that the field separator is solely a new line.)

Upvotes: 1

Related Questions