Easiest way to strip newline character from input string in pasteboard
MacosUnixShellMacos Problem Overview
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.
Macos Solutions
Solution 1 - Macos
pwd | tr -d '\n' | pbcopy
Solution 2 - Macos
printf $(pwd) | pbcopy
or
echo -n $(pwd) | pbcopy
Note that these should really be quoted in case there are whitespace characters in the directory name. For example:
echo -n "$(pwd)" | pbcopy
Solution 3 - Macos
I wrote a utility called noeol
to solve this problem. It pipes stdin to stdout, but leaves out the trailing newline if there is one. E.g.
pwd | noeol | pbcopy
…I aliased copy
to noeol | pbcopy
.
Check it out here: https://github.com/Sidnicious/noeol
Solution 4 - Macos
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