Search This Blog

Accessing clipboard in Linux terminal

On a day-to-day basis I am using Ubuntu, which means constantly switching between terminal window and ordinary graphical application like IDE, editors, etc. Often I need to copy a bit of text from IDE to terminal or back. At least in Ubuntu using inconsistent Ctrl + Shift + C (or V) key combination and mouse to select area in terminal is a bit painful. Life would be so much simpler if there was a command line utility to print current clipboard contents to standard terminal output and a second one to take standard input and put it into the clipboard. Life can be much simpler, have a look at xclip!
Without diving into details, start by defining the following aliases in your system (put them in ~/.bash_aliases right now, you'll love them):

alias ctrlc='xclip -selection c'
alias ctrlv='xclip -selection c -o'

ctrlc and ctrlv, sounds familiar? Of course aliases are completely arbitrary. Now run any bash command but pipe its output to ctrlc:

$ ps | ctrlc

Nothing happened? Open your favourite editor or any graphical application and hit Ctrl + V, like I just did in ReText Markdown editor:

That's right, the output of ps magically appeared in my Ubuntu clipboard. But there's more. Put any text you want in the clipboard using Ctrl + C and send it to standard output of your terminal:

$ ctrlv
Accessing clipboard in Linux terminal

These two simple commands show their real power when used together as part of larger pipe. Say you want to extract two most common IP addresses appearing in your access.log (example) and send them to your team mate over IRC or e-mail:

Step by step: take the first space-delimited field from access.log (IP), sort all IPs and count how many times each IP appears (uniq -c). Finally sort by the number of occurrences, take two most common (tail -n 2) and copy to clipboard.
But I would like to share yet another tip with you:

Pretty-printing (formatting) of XML and JSON in command line.

How many times you copied a piece of XML from logs or from SoapUI which was completely unreadable due to missing newlines and indentation? Suffer no more, say you have <a><b><c>C1</c><c>C2</c></b><d>D</d></a> in your clipboard. Try this:

And what if you want to put the formatted XML back to the clipboard? I think you already know... Let's try something more sophisticated. Unformatted XML and JSON is typically returned from all sorts of APIs (and we live in the API era). Good, APIs are for computers, not for humans.

Possibility to access system clipboard both-ways is a life saver when working a lot with the terminal. But it's even greater if you work with XML or JSON and you can simply type: ctrlv | xmlformat | ctrlc to replace unformatted clipboard content with pretty-printed version of it. I hope you'll enjoy