Is there some way to run whatever you copy to the 'clipboard' through some sort of filter? Ideally to strip out the trailing newline from something you copy, so that it doesn't auto-run in the terminal?

This is what it looks like when I copy the test in question, and I sometimes forget this is a new line.
enter image description here

  • I'm in the need for this too! – Nam G VU Dec 25 '19 at 5:12
  • so, this is still impossible as of today? seemingly trivial thing and no terminal emulator implements this? – Display Name Dec 30 '19 at 15:05
  • @DisplayName see accepted answer – Pureferret Dec 30 '19 at 15:06

Good modern terminals support bracketed paste: when you use the terminal's paste command, it sends special escape sequences around the clipboard content. If your shell supports bracketed paste, it'll paste the clipboard content including any control characters as-is, and in particular a trailing newline will not trigger the execution of the command.

Zsh ≥5.1 supports bracketed paste and has it on by default. Older versions can be taught. Bash ≥4.4 supports bracketed paste if you add set enable-bracketed-paste on to ~/.inputrc.

If your terminal or shell doesn't support bracketed paste, you could define a shell function that pastes without the trailing newline.

In zsh, the following command recalls the content of the clipboard, minus trailing newlines, and brings it up for editing (even if there are multiple lines):

print -z -- "`xsel -b`"

In bash, you can push the content of the clipboard minus trailing newlines to the history stack. After this, press Up to bring up the command for editing.

history -s -- "`xsel -b`"
  • This is beautiful solution! Working for me in Ubuntu 18.04! Thank you! – Nam G VU Dec 25 '19 at 5:15

Yes, use cat to paste in a file, do whatever you like and then execute it.

For this case:

$ cat > tmp
$ tr -d '\n' <tmp | xclip # this remove all "new line" characters 
                          #  and copy back to clipboard
  • And how could I use it on GUI level when I copy some command from browser (like Stack answer) to my shell... In fact I ruined my OS yesterday because of such copy-paste :) – Tomasz Kapłoński Feb 12 '18 at 14:26

This makes \ev insert the clipboard without newlines in bash 4.0 and later:

pasteline() {
  local input=$(xsel -b)

bind -x '"\ev": pasteline'

Replace xsel -b with pbpaste and install bash 4 in OS X.


I realized we can do it in one line, inspired from @RSFalcon7 answer

by using xsel, to copy to primary selection

cat | tr -d '\n' | xsel

[paste], 2 times[Ctrl-D]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.