|Tip 330||Pass Command-Line Output to GUI Apps|
This is a tip for hardcore command-line fans who like a little graphical user-interface goodness in their lives.
Piping Output into Default GUI Apps
As mentioned elsewhere, you can use the open command at the command line to open files in GUI applications (Tip 325, Start GUI Apps from the Command Line). The command open filename.txt will open filename.txt in TextEdit, for example.
However, the -f command-line switch will cause open to accept output piped from a command. For example, the following will pipe a detailed directory listing in a new document within TextEdit:
ls -la | open -f
Piping Output into a Specific App
To choose an application other than the default, specify it using the -a switch. I have an alternative text editor called TextMate installed on my system, for example, and the following pipes the directory listing to it:
ls -la | open -f -a TextMate
Piping Output into the Clipboard
Instead of specifying the open command, you can pass the output of a command to the clipboard, ready for pasting into another app. Simply use the pbcopy command.
ls -la | pbcopy
Typing Directly into the Clipboard
Should you want to, you can type text directly into the clipboard by specifying the pbcopy command on its own and hitting Return. Type what you want to enter into the clipboard (you can include carriage returns), and hit Control+D when you’ve finished.
Typing Directly into the “Find” Clipboard
OS X uses a separate clipboard for what appears in find and replace boxes. So, if you want to type something directly at the command line that you’d like to then search for within an app like TextEdit, you can use the following command—just replace “search phrase” with what you’d like to put in the clipboard:
echo search phrase | pbcopy -pboard find
Then switch to an app like TextEdit and hit Command+F, and you’ll find the text you typed waiting for you in the Find field.
This command could be used very effectively with the yank feature of Bash.
Inserting Clipboard Contents at the Command Line
It’s also possible to reverse the process described previously and paste the contents of the clipboard onto the command line or into a file using the pbpaste command. For example, the following will redirect the clipboard contents—which can come from anywhere, such as Microsoft Word—into a new file:
pbpaste > textfile.txt
Obviously, any formatting applied to the text is stripped out.
Again, you can add -pboard to output the “find” clipboard contents instead:
pbpaste -pboard find > textfile.txt