user10713428
user10713428

Reputation: 13

row to column using awk

I would like to know how I could transform the following ('Old') to 'New1' and 'New2' using awk:

Old:

5
21
31
4
5
11
12
15
5
19
5
12
5
.
.

New1:

5 21 31 4
5 11 12 15
5 19
5 12
. 
.

New2:

521314
5111215
519
512
. 
.

Thanks so much!

Upvotes: 0

Views: 78

Answers (4)

Ed Morton
Ed Morton

Reputation: 203169

With any awk:

$ awk -v ORS= '{print ($0==5 ? ors : OFS) $0; ors=RS} END{print ors}' file
5 21 31 4
5 11 12 15
5 19
5 12

$ awk -v ORS= -v OFS= '{print ($0==5 ? ors : OFS) $0; ors=RS} END{print ors}' file
521314
5111215
519
512

Upvotes: 0

jas
jas

Reputation: 10865

Requires gawk for multi-character RS:

$ awk 'BEGIN {RS="\n5\n"} {$1=$1; print (NR>1 ? 5 OFS $0 : $0)}' file
5 21 31 4
5 11 12 15
5 19
5 12   

For the second version, just set OFS to the empty string:

$ awk -v OFS="" 'BEGIN {RS="\n5\n"} {$1=$1; print (NR>1 ? 5 OFS $0 : $0)}' file
521314
5111215
519
512

Upvotes: 2

karakfa
karakfa

Reputation: 67467

some variation of @jas's script

$ awk -v RS="(^|\n)5\n" -v OFS='' 'NR>1{$1=$1; print 5,$0}' file
521314
5111215
519
512

$ awk -v RS="(^|\n)5\n" -v OFS=' ' 'NR>1{$1=$1; print 5,$0}' file
5 21 31 4
5 11 12 15
5 19
5 12

in the second one you don't have to set the OFS explicitly since it's the default value, otherwise both scripts are the same (essentially same as the other referenced answer).

Upvotes: 1

Kent
Kent

Reputation: 195029

To get new1:

awk '/^5/{printf "%s", (NR>1?RS:"")$0;next}{printf " %s",$0}END{print ""}' file

To get new2:

awk '/^5/{printf "%s", (NR>1?RS:"")$0;next}{printf "%s",$0}END{print ""}' file

Upvotes: 1

Related Questions