Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:~$ 
like image 696
Ankur Agarwal Avatar asked May 20 '26 21:05

Ankur Agarwal


2 Answers

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)

like image 159
doubleDown Avatar answered May 22 '26 16:05

doubleDown


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
like image 41
P.P Avatar answered May 22 '26 17:05

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!