Thursday, August 2, 2012

Command Line Copy/Paste

At times I find myself grabbing and copying some text from a GUI editor, and wanting to save it all into a file somewhere for command line access and manipulation (e.g. log files). My usual approach used to be one of the following (numbers in parentheses are the number of keystrokes used):
  1. Open Spotlight(2); Open TextEdit(2+O(1)+1); [PASTE](2); [SAVE](2); type in the new filename(N); Select WITH THE MOUSE to save it as a plain text file and NOT as an RTF as is TextEdit's freaking default setting, and click SAVE(3 mouse seeks, 3 clicks!); Close TextEdit(2 or 4, I close the window first with Command-W before Command-Q to avoid the file re-appearing when I open TextEdit the next time); Move this file to where I want it through Terminal. (O(N)). At least 15 keystrokes AND 3 mouse seek+clicks - it's a freaking long process for a task so punctual.
  2. type "vi <filename.txt>" in Terminal(4+N); Press "i" to enter INSERT mode(1); [PASTE] the contents(2); ESC, Save and Exit with ":wq"(6). 13+N keystrokes in total, much better considering the mouse is never needed.
The second option sounds way better, although sometimes when I copy some text many MB long, vi dutifully attempts to load it all up into memory and display it for me on the screen. This can take a while, plus for especially lengthy texts, it encourages dreaded pagination to kick in.

So I Googled around for a bit and found two shiny little gems that will redeem my inter-Terminal-GUI interfaces (at least on my Mac OS X):
  • pbcopy < inputStream
  • pbpaste > outputStream
As straightforward as they should be. 8+N keystrokes, and no further user interface required. Would be absolutely perfect to automate GUI tasks, if I knew how to handle GUI's from the command line in detail.

Credits where credit's due:

No comments:

Post a Comment