awk Help: Filter Multiple Entry & print in one line.

AWK Gurus,

data:

srvhcm01 AZSCI
srvhcm01 AZSDB
srvhcm01 BZSDB
srvhcm01 E2QDI31
srvhcm01 YPDCI
srvhcm01 YPDDB
srvhcm01 UV2FSCR
srvhcm01 UV2FSBI
srvhcm01 UV2FSXI
srvhcm01 UV2FSUC
srvhcm01 UV2FSEP
srvhcm01 UV2FSRE
srvhcm01 NASCI
srvhcm01 NASDB
srvhcm01 UV2FSSL
srvhcm01 UV2FSDI
srvhcm05 KASCI
srvhcm05 KASDB
srvhcm05 E2SCI
srvhcm05 YPSDB
srvhcm05 YPSCI
srvhcm05 AZDDB

Want to get output like this:

srvhcm01 AZSCI AZSDB BZSDB E2QDI31 YPDCI YPDDB UV2FSCR UV2FSBI UV2FSXI UV2FSUC UV2FSEP UV2FSRE NASCI NASDB UV2FSSL UV2FSDI 
srvhcm05 KASCI KASDB E2SCI YPSDB YPSCI AZDDB

Please advise with awk or sed,
Thanks a lot,

awk 'NR==1{p=$1; printf "%s ",$0; next}p==$1{ printf "%s ",$2;}p!=$1{printf "\n%s ",$0; p=$1; next}' filename
1 Like
awk 'p!=$1{if(p)print s; s=p=$1}{s=s OFS $2} END{print s}' file
1 Like

bipinajith,
This is a great code , it worked like charm.
Could you please explain how it work all together.

The 2nd part seems more compliated where p!=$1 ,

Thanks a lot again.

---------- Post updated at 07:05 PM ---------- Previous update was at 07:01 PM ----------

Scrutinizer,

This is also a great code.It worked like a charm and indeed got the last Carriage return that I didnt get in the other solution.

awk 'p!=$1{if(p)print s; s=p=$1}{s=s OFS $2} END{print s}' file

This looks more complicated, can you please explain little bit , like

if(p)print s

& OFS portion,
Thanks a lot again.

Inserted newline at end:

awk ' NR==1 {           # If first record
   p=$1;                # Set p = field 1
   printf "%s ",$0;     # printf entire record in same line
   next;
} p==$1 {               # if p == field 1
   printf "%s ",$2;     # printf only field 2 in same line
} p!=$1 {               # if p != field 1
   printf "\n%s ",$0;   # printf entire record in newline
   p=$1;                # Set p = field 1
   next;
} END {
   printf "\n";
}' filename
1 Like

if(p)print s means if the previous result p is not empty then print the string s. OFS is the output field separator which defaults to a single space..

1 Like

Thanks bipinajith for the detail explanation:

what is the function of next; is it for loop.

---------- Post updated at 08:35 PM ---------- Previous update was at 08:33 PM ----------

Scrutinizer ,
Thanks again, ..You guys are awesome coder & programmer. Thanks.

The next statement directs awk to stop processing current record and work on next record.

Hence no further conditions are checked or actions are performed for the current record.