1

I know I can use RS="" to set record separator as multiple consecutive empty lines. However if those lines contain space or tab characters it will not work. I'm thinking to set RF as some kind of regular expression to do the match. But it's hard, since in this case often \n will be used as the field separator FS. Any suggestions?

2 Answers 2

4

Here is a way to do it:

awk '!NF {$0=""}1' file | awk -v RS="" '{print NR,$0}'

The first awk counts the fields on the line. This will be 0 if you have blank lines or lines with spaces and tabs only. Then it just change the line to nothing. After this you can use the RS=""


Here is a gnu awk version (due to multiple characters in RS):

awk -v RS="\n([[:space:]]*\n)+" '{print NR,$0}' file

It may work without parentheses, but I am not sure if all will be covered then:

awk -v RS="\n[[:space:]]*\n+" '{print NR,$0}' file
2
  • 2
    To clarify what Jotne alludes to in the answer: according to the awk standard (pubs.opengroup.org/onlinepubs/9699919799/utilities/…), "If RS contains more than one character, the results are unspecified". Using multiple character in RS requires that a specific version of awk be used, and the usage here works with gawk. Aug 23, 2014 at 14:51
  • Thanks Jotne! Actually I'm using the default awk on Mac and can't make it work. After installed gawk by brew install gawk I can use the command to get what I want (based on your version): gawk 'BEGIN {RS = "\n(( |\t)*\n)+"; FS = "\n"} {print $2}' multiaddress.txt.
    – user130268
    Aug 23, 2014 at 19:00
2

With GNU awk for multi-char RS:

awk -v RS='\n(([[:space:]]*\n)+|$)' '{print NR, "<" $0 ">"}' file

e.g.

$ awk '{print NR, "<" $0 ">"}' file
1 <a>
2 <  b>
3 <   >
4 < c>

$ awk -v RS='\n(([[:space:]]*\n)+|$)' '{print NR, "<" $0 ">"}' file
1 <a
  b>
2 < c>
1
  • 1
    Thanks Ed for the help!
    – user130268
    Aug 23, 2014 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.