Ankur Agarwal
Ankur Agarwal

Reputation: 24788

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:~$ 

Upvotes: 2

Views: 1781

Answers (2)

doubleDown
doubleDown

Reputation: 8408

ORS is appended to the end of each output record. 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

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

When you print them, each record is terminated with ORS, (), so

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)

Upvotes: 7

P.P
P.P

Reputation: 121427

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. Just remove the blank line from your input file.

Side note: you don't have to cat the file then pipe to awk. Simply use awk:

awk ' .... ' file

Upvotes: 2

Related Questions