Selective grouping

I have a text file in this format.

[server1.domain.com]
Group: AAA
Notes: IP : 11.11.11.11

#User xxxxxxxxx

#Password aaaaaaaaaaaaaaaa


[server2.domain.com]
Group: AAA
Notes: IP : 11.11.11.22

#User yyyyyyyyyyyyy

#Password bbbbbbbbbbbbb



[server3.domain.com]
Group: AAA
Notes: IP : 11.11.11.33

#User zzzzzzzzzzz

#Password cccccccccccccccc

I need a script/sed/awk that when applied on the above test file, it will print as follows.

xxxxxxxxx@11.11.11.11
yyyyyyyyyyyyy@11.11.11.22
zzzzzzzzzzz@11.11.11.33

Try this:

awk '
    /Notes:/ { ip = $NF; next; }
    /User/  { printf( "%s@%s\n", $NF, ip ); next; }
' input-file 
1 Like
# awk '{print $9"@"$7}' RS="\n\n\n" text
xxxxxxxxx@11.11.11.11
yyyyyyyyyyyyy@11.11.11.22
zzzzzzzzzzz@11.11.11.33
1 Like

Note: In standard awk RS can only be single character. Only in gawk and mawk can RS also be a regex (so it can also be multiple characters).

and the sed

# sed -n '/Notes\|User/{N;s/\n//;s/.* //;N;s/\(.*\)\n.* \(.*\)/\2@\1/gp}' text
xxxxxxxxx@11.11.11.11
yyyyyyyyyyyyy@11.11.11.22
zzzzzzzzzzz@11.11.11.33
1 Like

Thanks, its working.

A bit modification needed. The output should be formatted as

alias server1.domain.com='ssh xxxxxxxxx@11.11.11.11' 
alias server2.domain.com='ssh yyyyyyyyyyyyy@11.11.11.22' 
alias server3.domain.com='ssh zzzzzzzzzzz@11.11.11.33'
awk '/IP/{P=$NF;i=1};i&&/#User/{print $2"@"P;i=0}' filename
xxxxxxxxx@11.11.11.11
yyyyyyyyyyyyy@11.11.11.22
# awk -v x="'" '/server/{gsub("[][]","");s=$0}
/Notes/{s1=$NF}/User/{s2=$NF;print "alias",s"="x"ssh",s2"@"s1 x}' infile
alias server1.domain.com='ssh xxxxxxxxx@11.11.11.11'
alias server2.domain.com='ssh yyyyyyyyyyyyy@11.11.11.22'
alias server3.domain.com='ssh zzzzzzzzzzz@11.11.11.33'
1 Like

ygemici,

Thanks a lot !