[英]row to column using awk
I would like to know how I could transform the following ('Old') to 'New1' and 'New2' using awk: 我想知道如何使用awk将以下内容(“旧”)转换为“ New1”和“ New2”:
Old: 旧:
5
21
31
4
5
11
12
15
5
19
5
12
5
.
.
New1: NEW1:
5 21 31 4
5 11 12 15
5 19
5 12
.
.
New2: NEW2:
521314
5111215
519
512
.
.
Thanks so much! 非常感谢!
Requires gawk for multi-character RS
: 需要多字符RS
gawk:
$ 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: 对于第二个版本,只需将OFS
设置为空字符串:
$ awk -v OFS="" 'BEGIN {RS="\n5\n"} {$1=$1; print (NR>1 ? 5 OFS $0 : $0)}' file
521314
5111215
519
512
To get new1
: 要获取new1
:
awk '/^5/{printf "%s", (NR>1?RS:"")$0;next}{printf " %s",$0}END{print ""}' file
To get new2
: 要获取new2
:
awk '/^5/{printf "%s", (NR>1?RS:"")$0;next}{printf "%s",$0}END{print ""}' file
some variation of @jas's script @jas脚本的一些变化
$ 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). 在第二个脚本中,您不必显式设置OFS
因为它是默认值,否则,两个脚本都相同(基本上与另一个引用的答案相同)。
With any awk: 任何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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.