Easiest way to strip newline character from input string in pasteboard

Viewed 16289

Hopefully fairly straightforward, to explain the use case when I run the following command (OS X 10.6):

$ pwd | pbcopy

the pasteboard contains a newline character at the end. I'd like to get rid of it.

4 Answers

For me I was having issues with the tr -d '\n' approach. On OSX I happened to have the coreutils package installed via brew install coreutils. This provides all the "normal" GNU utilities prefixed with a g in front of their typical names. So head would be ghead for example.

Using this worked more safely IMO:

pwd | ghead -c -1 | pbcopy

You can use od to see what's happening with the output:

$ pwd | ghead -c -1 | /usr/bin/od -h
0000000      552f    6573    7372    732f    696d    676e    6c6f    6c65
0000020      696c
0000022

vs.

$ pwd | /usr/bin/od -h
0000000      552f    6573    7372    732f    696d    676e    6c6f    6c65
0000020      696c    000a
0000023

The difference?

The 00 and 0a are the hexcodes for a nul and newline. The ghead -c -1 merely "chomps" the last character from the output before handing it off to | pbcopy.

$ man ascii | grep -E '\b00\b|\b0a\b'
     00 nul   01 soh   02 stx   03 etx   04 eot   05 enq   06 ack   07 bel
     08 bs    09 ht    0a nl    0b vt    0c np    0d cr    0e so    0f si
Related