Terminal 101: Copy & Paste with Files in the Terminal

Every Monday, we’ll show you how to do something new and simple with Apple’s built-in command line application. You don’t need any fancy software, or a knowledge of coding to do any of these. All you need is a keyboard to type ’em out!

Copy-and-paste in OS X is powerful, but nothing can match the copy-paste abilities of the Terminal commands we’ll cover today. Using some simple piping techniques coupled with the pbpaste and pbcopy commands, we have the ability to copy and paste directly with text files from the Terminal. This means that you can instantly copy a file’s contents to the clipboard without first having to open the file. Same goes for pasting directly to a file without having to create it first.

Continue reading, and we’ll show you how it’s done.

1. Copy from a File

To copy text from a file on your computer to your clipboard for pasting into another application is easy. Simply navigate to the directory that contains the fie, then issue the following command, replacing “file.txt” with the path and file that you wish to copy from.

pbcopy < file.txt

When you run this command, the text that is in file.txt will be instantly whisked away to your clipboard, where you can use the standard OS X paste command (Command + V) to paste the text into any application on your Mac.

2. Paste to a File

If you want to go the other way, you can do that as well. Let’s say that you have some text copied to your clipboard, and wish to make a new text file from it, but don’t want to go throughout he process of opening an application, saving the file, etc.

You can simply run the following command, replacing “file.txt” with the name of the file you wish to create using the text in your clipboard.

pbpaste > file.txt

After running this command, a new file will be created in your current working directory that contains the text that you had in your clipboard. Pretty nifty, eh?

Cory Bohon is a freelance technology writer, indie Mac and iOS developer, and amateur photographer. Follow this article’s author on Twitter.