[英]Awk command to format text output with custom record separator and field Separator
I have a file which has the data in the following manner : 我有一个文件,该文件具有以下方式的数据:
1
2
3
end
4
5
6
I want an output in the form : 我想要以下形式的输出:
1 2 3
4 5 6
here the string "end" represents the record separator. 这里的字符串“ end”代表记录分隔符。 I am new to UNIX and used Awk to achieve this, I am sure there can be much easier and a better way. 我是UNIX的新手,并且使用Awk来实现这一点,我相信可以有更简单,更好的方法。 Here is my attempt: 这是我的尝试:
awk 'BEGIN {RS="end\n"; FS="\n"} { print $1 "\t" $2 "\t" $3 "\t" $4'} atestfile.awk
Personally I'd write it like this: 我个人会这样写:
awk -v RS='end' -v OFS='\t' '{$1=$1}1' file
The differences are that I've used -v
to specify the record separator RS
and the output field separator OFS
. 区别在于我使用-v
来指定记录分隔符RS
和输出字段分隔符OFS
。 I've also used $1=$1
to make awk "touch" each record (so that the format is changed to use OFS
) and 1
at the end as a shorthand for {print}
(since 1
is always True and the default action of awk
on True is to print the record). 我还使用$1=$1
使awk“触摸”每条记录(以便将格式更改为使用OFS
),最后使用1
作为{print}
的简写形式(因为1
始终为True且默认操作为在True上awk
将打印记录)。
I'd probably use perl
(and yes, I know that's not quite what you asked, but given it's standard on Unix, I'll offer it anyway). 我可能会使用perl
(是的,我知道那不是您所要的,但鉴于它是Unix上的标准,无论如何我都会提供它)。
use strict;
use warnings;
#read STDIN or a filename designated on command line.
while (<>) {
#replace linefeeds with spaces.
s/\n/ /g;
#Check for presence of "end"
if (m/end/) {
#insert linefeed
print "\n";
}
else {
print;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.