开发者

Easiest way to strip newline character from input string in pasteboard

Hopefully fairly straightforward, to explain the use case 开发者_JAVA百科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.


pwd | tr -d '\n' | pbcopy


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


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


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


We can first delete the trailing newline if any, and then give it to pbcopy as follows:

your_command | perl -0 -pe 's/\n\Z//' | pbcopy

We can also create an alias of this:

alias pbc="perl -0 -pe 's/\n\Z//' | pbcopy"

Then the command would become:

pwd | pbc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜