简体   繁体   English

在awk中使用记录分隔符

[英]Using record separators in awk

I have 我有

$ cat awktestf 
a++
b++
c++

I am doing and I get 我在做,我得到

cat  awktestf | awk 'BEGIN { RS="++" ; OFS="@"; ORS="()" } { print $0 } END {print "I am done" }'
a()
b()
c()
()I am done()abc@abc:~$ 

My question is why am I getting an extra () at the end? 我的问题是,为什么最后我要得到一个额外的()?

Even this does not work: 即使这样也不起作用:

$ echo 'a++
> b++
> c++' | awk 'BEGIN { RS="++" ; OFS="@"; ORS="()" } { print $0 } END {print "I am done" }'
a()
b()
c()
()I am done()abc@abc:~$ 

ORS is appended to the end of each output record. ORS附加到每个输出记录的末尾。 Hence your "I am done" ends with () . 因此,您的“我完成了”以()结尾。


Misunderstood the question the first time. 第一次误解了这个问题。

This 这个

a++
b++
c++

translates to 转换为

a++\nb++\nc++\n

After splitting into records using RS , you get these records 使用RS拆分成记录后,您将获得这些记录

  1. a 一种
  2. \\nb \\ nb
  3. \\nc \\ nc
  4. \\n \\ n

When you print them, each record is terminated with ORS , () , so 打印它们时,每个记录都以ORS ()终止。

a()\nb()\nc()\n()

You added "I am done" 您添加了“我完成了”

a()\nb()\nc()\n()I am done()

Hence this is displayed as 因此,这显示为

a()
b()
c()
()I am done()

(Since the last line does not end with a newline, your prompt shows on the same line) (由于最后一行不以换行符结尾,因此提示显示在同一行上)

Probably you have a blank line at the end of the your file. 文件末尾可能有一个空白行。

Since OFS is set to () , it gets printed after every line that's printed to the output. 由于OFS设置为() ,因此它将在打印到输出的每一行之后打印。 Just remove the blank line from your input file. 只需从输入文件中删除空白行即可。

Side note: you don't have to cat the file then pipe to awk. 旁注:您不必先cat文件,再通过管道传输到awk。 Simply use awk : 只需使用awk

awk ' .... ' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM