2

I have:

alias pbcopy='xclip -selection clipboard -in'

This allows me to do things like date | pbcopy, to get the date in the clipboard.

However, I also get a newline character at the end of the date which needs to be manually removed after pasting.

How can I remove the final newline (and only the final newline) from a pipeline?

Tom Hale
  • 40,825
  • 36
  • 187
  • 242

1 Answers1

1

Pipe through:

sed -z '$ s/\n$//'

sed won't add a \0 to then end of the stream if the delimiter is set to NUL via -z, whereas to create a POSIX text file (defined to end in a \n), it will always output a final \n without -z.

Eg:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//'; echo tender
foo
bartender

And to prove no NUL added:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//' | xxd
00000000: 666f 6f0a 6261 72                        foo.bar

To remove multiple trailing newlines, pipe through:

sed -Ez '$ s/\n+$//'
Tom Hale
  • 40,825
  • 36
  • 187
  • 242