41

this is the command responsible for adding a new line to the string

echo "string" | xclip -selection clipboard

3 Answers3

62
echo -n "string" | xclip -selection clipboard

I should probably have elaborated a bit. The default for echo is to output the string AND a newline. -n suppreses the latter.

tink
  • 14,342
  • 4
  • 46
  • 50
32

The more generic solution is to ignore new lines regardless of the input source. For instance, the common use case is to copy to the clipboard a path of the current directory. The command

pwd | xclip -selection clipboard

copies the new line character and this is often not what we want. The solution is the following:

pwd | xargs echo -n | xclip -selection clipboard

You can create an alias to make it more convenient:

alias xclip='xargs echo -n | xclip -selection clipboard'

and from now on use:

pwd | xclip # copied without new line
echo "foo" | xclip # copied without new line
Michael Szymczak
  • 1,216
  • 13
  • 15
  • how does adding `pwd` make this "more generic"? :) – tink Nov 28 '18 at 18:25
  • 4
    If you read carefully, you can see that the generic solution refers to "ignore new lines regardless of the input source". The pwd part is shown as an example and "common use case" why you may want to do it. The last example uses echo as well. – Michael Szymczak Dec 01 '18 at 16:17
  • And what suggests to you that one wants to get rid of ALL newlines? `(pwd; pwd)| xargs echo -n | xclip -selection clipboard` – tink Apr 16 '22 at 18:23
22

Since version 0.13 of xclip, you have a generic way that will preserve the inner new lines with the option r or rmlastnl.

So you will have:

pwd | xclip -r # copied without new line
echo "foo" | xclip -r # copied without new line
ps | xclip -r # copied without the last new line!
rools
  • 1,539
  • 12
  • 21