0

Is there something I can do so that whenever I pipe something into xclip it does not include a new line at the end?
As a workaround, I am using echo -n $(CMD_TO_COPY) | xclip, but it's kind of annoying having to type all of this each time I want to copy something.

Romeo Ninov
  • 17,484

2 Answers2

3

According to the man page, xclip has a -rmlastnl (-r) option that will do exactly what you want:

echo hello | xclip -i -r
larsks
  • 34,737
1

Though xclip since version 0.13 does have an option to remove a trailing newline as already noted by larsks, you could also always define a function that does the processing you want like:

clipboard() { printf %s "$(cat -- "$@")" | xclip -sel c; }
clipboard() { printf %s "$(cat -- "$@")" | xsel -b; }

(here, command substitution removes all trailing newline characters and in some shells including bash, also all the NUL ones).

Or to remove only one trailing newline like xclip -r does:

clipboard() { cat -- "$@" | perl -pe 's/\n$// if eof' | xclip -sel c; }

And use as:

cmd | clipboard
clipboard <<< "$var"
clipboard some-file and-some-other

In any case, using echo, or unquoted command substitutions as in your echo -n $(CMD_TO_COPY) approach is not correct.