Saturday, April 12, 2008

Join multiple lines using AWK


Some lines in output.txt are broken.

$ cat output.txt
a:b:c:1:2:3:2.3:henry
s:d:f:2:1:4:
54:user5
d:q:w:5:6:
3:5.2:alex
y:m:n:3:4:1:5.6:eiam

Output Required:
----------------
a:b:c:1:2:3:2.3:henry
s:d:f:2:1:4:54:user5
d:q:w:5:6:3:5.2:alex
y:m:n:3:4:1:5.6:eiam


$ awk '
BEGIN {
FS=":";
maxFLD=8;
}
{
while (NF < maxFLD || $0 ~ /\:$/ ) {
getline record;
$0 = $0 record
}
print $0
}
' output.txt


** While current record ($0) is less than 8 fields (NF) or is incomplete (ending with :), update the current record by appending the next record.

2 comments:

awkseeker said...

cool you are! this code bring me more easy.
thank jadu

Linux Tutorial said...

Hi Jadu, I have a data as mentioned below.

host_name Server1.domain.com
contacts DL - Desktop
contact_groups ravi, raj, rahim
host_name Server2.domain.com
contact_groups DL-Server
host_name Server3.domain.com
host_name Server4.domain.com
contacts Services,helpdesk,manager

Required Output is below.

host_name Server1.domain.com, contacts ravi,raj,rahim, Contact_group DL - Desktop
host_name Server2.domain.com contact_groups DL - Server
host_name Server3.domain.com
host_name Server4.domain.com contacts services,helpdesk,manager

Can you please help me out to achieve this output.

© Jadu Saikia www.UNIXCL.com