Copy/paste in Linux using xclip
When working on the Linux desktop, how do you typically copy all or part of a text file?
Most likely, you open the file in a text editor or print in terminal using cat command, select all or only the text you wish to copy, and paste it somewhere.
There is another way of doing it. The xclip command-line utility tool makes the operation a little more efficient.
Xclip is a command line interface to X selections i.e. Clipboard. Xclip reads the data from one or more files and makes the data available as an X selection for pasting the data into X applications. If no files are specified, it reads data from the standard input. It can also print the X selection to the standard output.
In Linux, the clipboards are known as “Selections” and there are three types of clipboards available in X11 window system. PRIMARY, SECONDARY, or CLIPBOARD.
For more info about Selections, Check below links:
Installing xclip
Xclip is available in the official repositories of most modern Linux distributions.
For Alpine Linux:
sudo apk add xclip
For Arch Linux
sudo pacman xclip
For Debian, Ubuntu, Mint
sudo apt install xclip
Xclip command examples
To copy the output of a command to clipboard:
echo "text to copy" | xclip -sel clip
and you can paste it using Ctrl+Shift+V.
Now let’s say you have a file with 1000 lines on a server and you wanted to copy and paste it to another server.
what options do you have?
- copy the file using scp and rsync. (need to setup ssh key)
- open file in editor and select the lines and copy it. (selecting, copying and pasting is a bit of work. sometime you need to try more than once)
- print the file in terminal using cat command select text and copy it. (selecting, copying and pasting is a bit of work. sometime you need to try more than once)
4. Or you can use xclip to copy contents of file and paste it wherever you want.
xclip -sel clip your_file_name
another quick example is you just wanted to copy last 50 lines of log file. simply combine xclip with tail
tail -n 50 logfile.log | xclip -sel clip
and you can paste it anywhere you want.
Is that the extent of xclip’s capabilities? Certainly not. I’m sure you can come up with a few more to suit your needs.