Blog

Thoughts from my daily grind

Copy Paste Like Geek using XClip

Posted by Ziyan Junaideen |Published: 06 September 2020 |Category: Linux
Default Upload |

Whats you routine to copy paste contents from a file, part of a file or the output from a command? Opening a file in an appropriate application/editor, searching, selecting and copying is fast, but not the most efficient way to handle things. The terminal is always faster, if you care to familiarize your self with some tools.

In the Linux/Mac OS world this tool is xclip.

Installation

All major distributions have their own package manager and you can install xclip from it. I am on Ubuntu and for any Debian based OS this should work.

sudo apt update
sudo apt install xclip

or use the following if you are on Mac OS. I assume you have already installed Homebrew which is an awesome package manager for Mac OS, it is not even close to apt in the Linux world though.

brew install xclip

For Windows I think there is a tool called clip. But since I don't use Windows, I can't be sure. It is not the same as this, that much I know.

Basics

You have 2 methods to copy paste in Linux. One way is to select the text you want to copy, use the middle button of the mouse to copy, then go to where you want to paste, and press the middle button again. This is the middle button copy. I am not sure if this is available in MacOS. The other method is the good old way of copying things to the clipboard. xclip supports both these methods.

Copies the file file as if you would have used the mouse middle button:

xclip <File Name>

Copies the file to the clipboard:

xclip --selection clipboard <File Name>

Using with other terminal tools

A tool like xclip by it self is less useful. Most system administration jobs will require some sort of processing. You can pair xclip with other utilities as well using pipes.

cat ~/.ssh/id_rsa.pub | xclip

In the above example cat spits out the file content to the terminal. We then pipe (|) that output to xclip which in turn copies it to the clipboard.

I also find xclip very useful to copy stack traces from log files.

tail -n 1000 log/production.log | grep -A 50 -B 5 "TokenExpiredError" | xclip -selection clipboard

What this command basically does is to get the last 1000 lines in the log/production.log file (tail -n 1000 log/production.log) and then look for TokenExpiredError (pattern) and get 5 lines above it (before - -B 5) and 50 lines after it (-A 50) and copy it to the clipboard.

Conclusion

xclip is a very useful utility. Its some thing every Linux user should get familiar with. If you are thinking its stupid, I was there too. But I assure you one day you will thank your self for learning its use.

Tags
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments