How to make xclip strip newline from the output piped to it?
Asked Answered
C

3

43

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

echo "string" | xclip -selection clipboard
Codger answered 4/6, 2013 at 21:41 Comment(3)
Suggest editing the title of this question to something like 'Prevent xclip from appending newline.' It's a great question, it was just hard to find!Viburnum
Good question, thanks!Charlatanism
The question has been fixed. Just took some 10.5 years...Boomkin
G
66
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.

Geyer answered 4/6, 2013 at 21:54 Comment(4)
if you wish to copy current path echo -n $(pwd) | xclip -selection clipboardZimmerman
one improvement for previous command echo -n ${PWD/ /\\ } | xclip -selection clipboard backslashes white spacesZimmerman
see the answer below by @rools for a more generic solution using xclip -rIre
@Ire - see answers in historical context. That option didn't exist back then. 0.13, which rools references, was released 2016, not 2013 ... I have been using -r for a while now.Geyer
G
35

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
Goering answered 11/7, 2015 at 12:36 Comment(3)
how does adding pwd make this "more generic"? :)Geyer
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.Goering
And what suggests to you that one wants to get rid of ALL newlines? (pwd; pwd)| xargs echo -n | xclip -selection clipboardGeyer
L
25

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!
Lahnda answered 7/5, 2017 at 9:42 Comment(4)
Requires version 0.13 thoughOdyssey
Thanks. I will add that in my answer.Lahnda
the -r did the trick fro me. would have helped if i fully read the manDynel
It's been a while since xclip 0.13. This should be the accepted answer and people should update.Sabol

© 2022 - 2024 — McMap. All rights reserved.