Skip to content

Instantly share code, notes, and snippets.

@ryan-williams
Last active March 31, 2016 14:44
Show Gist options
  • Select an option

  • Save ryan-williams/a585d0965f43264b1c3744cdbe45c8a3 to your computer and use it in GitHub Desktop.

Select an option

Save ryan-williams/a585d0965f43264b1c3744cdbe45c8a3 to your computer and use it in GitHub Desktop.
How to make perl match a run of spaces and newlines?
# File "bar"'s whitespace consists only of spaces and newlines.
$ cat bar
1, 2,
3,
4
# All attempts to replace consecutive runs of whitespace (spaces and newlines) with 'S'
# result in \n being replaced by one 'S', and spaces that follow it replaced by another 'S'.
# Desired output: 1,S2,S3,S4S
# Actual output: 1,S2,SS3,S4S
$ cat bar | perl -pe 's/\s+/S/g'
1,S2,SS3,S4S
$ cat bar | perl -pe 's/\s+/S/gm'
1,S2,SS3,S4S
$ cat bar | perl -pe 's/\s+/S/gms'
1,S2,SS3,S4S
$ cat bar | perl -pe 's/[ \n]+/S/gms'
1,S2,SS3,S4S
$ cat bar | perl -pe 's/[ \n]+/S/gm'
1,S2,SS3,S4S
$ cat bar | perl -pe 's/[ \n]+/S/g'
1,S2,SS3,S4S
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment