18 Jan 2011

Running a filter on text in clipboard

The power (or beauty, if you want to call it that way) of Unix command-line interface is not only because of the available commands, but also because of the way we can combine simple commands to do complex things.  Filters are a great example.  In the Unix world we can find many powerful commands that expose functionality that is available only to programs via APIs.  xsel is a great example.  With xsel command, we can inspect and manipulate the contents of clipboard from the command line.

I often have some text -- maybe in a simple text editor (like Kate or GEdit) or in the browser.  I want to use that text in a different program, but with some modifications applied to it.  For example I might want to convert all tab characters in that text to 2 spaces.  Today I wrote a one-line shell script (called run-on-clipboard) that would let me run any filter on the text in clipboard.  Here's the script:
#!/bin/sh
#
# Runs a "filter" on clipboard contents.  Can be used to make arbitrary changes
# to the text in clipboard.  For example, to convert all tabs in the clipboard
# text to two spaces, you can run:
#    run-on-clipboard sed 's/\t/  /g'

xsel -b | "$@" | xsel -bi
To convert tabs to spaces, I would copy the original text into clipboard and run the following command from a terminal:
  run-on-clipboard sed 's/\t/  /g'
This would change the clipboard contents, so pressing Ctrl+V in any program now will paste the text with tabs replaced with spaces.

No comments:

Post a Comment