Wednesday, May 20, 2009

Combine related consecutive lines - awk


Input file:

$ cat file.txt
ID502,
Kia,
class v,
pass

ID506,
Nill,
class v,
fail
ID902,
Herry,
class vi,
pass

Output required:
Combine the consecutive lines related to a particular student ID (^ID field) in single line. i.e. required output:

ID502,Kia,class v,pass
ID506,Nill,class v,fail
ID902,Herry,class vi,pass

Awk solution:

$ awk 'NR > 1 && /^ID/{print ""}
{printf $0}
END {print ""}
' file.txt


Related post:

- Combine every 3 lines as one line using awk
- Merging lines using awk in bash
- Split a file into sub-files based on start pattern - awk

2 comments:

Nathan said...

and as usualy , my bash / non awk solution :

#!/bin/bash


while read LINE
do

if [[ $LINE =~ ^ID.* ]]
then

printf "\n%s" "$LINE"

else

printf "%s" "$LINE"

fi

done < <(sed -nr '/^$/d;p' file.txt)

echo "" # required for the ending newline

awkseeker said...

awk seem to be more simple and effective than bash.
Thank Jadu

© Jadu Saikia www.UNIXCL.com