Monday, July 14, 2008

Merging lines using awk - bash


Input file:

$ cat myfile.txt

unix,bash
,scripting
awk is powerful
u1,u2
,u3,u4,u5


Objective: Merge the lines starting with comma "," with the previous line.
i.e. the output required.

unix,bash,scripting
awk is powerful
u1,u2,u3,u4,u5


Awk solution:

$ awk 'END { print r }
r && !/^,/ { print r; r = "" }
{ r = r ? r $0 : $0 }
' myfile.txt

3 comments:

awkseeker said...

Could you explain the code?

Rashmi said...

Input:
drwxr-xr-x 2 root root 140288 Jan 29 02:12 10.187.0.4
drwxr-xr-x 2 root root 558080 Jan 29 21:04 10.187.0.4
drwxr-xr-x 2 root root 145920 Jan 29 21:04 10.187.0.5
drwxr-xr-x 2 root root 925696 Jan 29 21:04 10.187.0.5
drwxr-xr-x 2 root root 148480 Jan 29 21:10 10.187.0.6
drwxr-xr-x 2 root root 558080 Jan 29 21:04 10.187.0.6
drwxr-xr-x 2 root root 123392 Jan 29 01:08 10.187.0.7


Desired output:
10.187.0.4 Jan 29 02:12 Jan 29 21:04

Unknown said...

@Rashmi_9561611688 , could you please provide more details on the requirement here, thanks.

© Jadu Saikia www.UNIXCL.com