从纸板输入字符串中去除换行符的最简单方法

当我运行以下命令(OS X 10.6)时,我希望能够相当简单地解释用例:

$ pwd | pbcopy

纸板的末尾有一个换行符,我想把它去掉。

16840 次浏览

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