8

How do you tell awk to use a # character by itself in a line as record separator? The problem is you can't say RS="^#$" because ^ matches the beginning of the file, not the beginning of a line, and RS="#\n" doesn't work either because it matches # characters that aren't at the beginning of a line.

$ data='#
first record, first field
first record, second field
#
second record, first field#
second record, second field
'

Then print the first field of each record, using RS="#\n":

$ printf "%s" "$data" | awk '
  BEGIN { RS="#\n"; FS="\n" }
  /./ {print $1}
  '
first record, first field
second record, first field
second record, second field

The last line is wrong because it's not the first field but the second. The intended output was

first record, first field
second record, first field#
8
  • 1
    Could you please also provide an example of the output you require
    – roaima
    Mar 21, 2015 at 11:41
  • so your data looks like line one#line two#line three?
    – Skaperen
    Mar 21, 2015 at 11:48
  • and RS="#" does what?
    – Skaperen
    Mar 21, 2015 at 11:48
  • @Skaperen no, the data looks like #\nrecord one\n#\nrecord two and each record consists of multiple \n-separated fields.
    – Ernest A
    Mar 21, 2015 at 11:55
  • RS='#\n' should work afaik - although it will treat the initial # as terminating an empty record (i.e. all the NR values will be "off" by one) Mar 21, 2015 at 12:29

1 Answer 1

7

Here's one way of doing it in awk:

$ printf "%s\n" "$data" | 
    awk -F'\n' -v RS='(^|\n)#\n' '/./ {print $1}' 
first record, first field
second record, first field#

The trick is to set the record separator to either the beginning of the file (^), or a newline, followed by a # and another newline \n.


2
  • 1
    Note the NRs will be one-off in this case (try replacing /./ with NR==1). I think the easiest solution would be to have the file/data ending - instead of starting - with a # on a separate line. Then \n#\n could be used as RS and it would work properly. Mar 21, 2015 at 13:33
  • @don_crissti I just copied that from the OP. I am assuming they're using it to avoid blank lines so NR==1 won't work if there are more blank lines further down.
    – terdon
    Mar 21, 2015 at 13:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .