Skip to main content
added 367 characters in body
Source Link
Stéphane Chazelas
  • 584.8k
  • 96
  • 1.1k
  • 1.7k

With gawk (using EREs similar to grep -E):

gawk 'RT && '/pattern/' && RT' file

RT in gawk contains what is matched by RS the record separator. With the default value of RS (\n) that would be \n except for a non-delimited last record where RT would then be empty.

With perl (perl REs similar to grep -P where available):

perl -ne 'print if /\n\zpattern/ && /\n\z/'

Note that contrary to gawk or grep, perl by default does work on bytes not characters. For instance, it's . regexp operator would match on each of the two bytes of a UTF-8-encoded £. For it to work on characters as per the locale's definition of characters like for awk/grep, you'd use:

perl -Mopen=locale -ne 'print if /pattern/ && /\n\z/'

With gawk (using EREs similar to grep -E):

gawk 'RT && /pattern/' file

With perl (perl REs similar to grep -P where available):

perl -ne 'print if /\n\z/ && /pattern/'

With gawk (using EREs similar to grep -E):

gawk '/pattern/ && RT' file

RT in gawk contains what is matched by RS the record separator. With the default value of RS (\n) that would be \n except for a non-delimited last record where RT would then be empty.

With perl (perl REs similar to grep -P where available):

perl -ne 'print if /pattern/ && /\n\z/'

Note that contrary to gawk or grep, perl by default does work on bytes not characters. For instance, it's . regexp operator would match on each of the two bytes of a UTF-8-encoded £. For it to work on characters as per the locale's definition of characters like for awk/grep, you'd use:

perl -Mopen=locale -ne 'print if /pattern/ && /\n\z/'
Source Link
Stéphane Chazelas
  • 584.8k
  • 96
  • 1.1k
  • 1.7k

With gawk (using EREs similar to grep -E):

gawk 'RT && /pattern/' file

With perl (perl REs similar to grep -P where available):

perl -ne 'print if /\n\z/ && /pattern/'