: Learning GNU Emacs, 3rd Edition

5.2.5 Running Shell Commands on Files

5.2.5 Running Shell Commands on Files

While Dired's implementation of diff is useful (and there are implementations of chmod, grep, and find as well), in a more general sense, you can perform any command on a file by pressing an exclamation point (!). For example, let's alphabetize the phone list file using the sort command.

Move to the phone file and press !


Emacs asks what command you want to run (Mac OS X).

Type: sort


Emacs displays the output from the command in a separate window (Mac OS X).

Usually, asterisks (*) and question marks are used as wildcards in commands. In Dired, they have a special meaning. An asterisk means "use the file I'm on or the files I've marked"; that way you don't have to type filenames explicitly. When multiple files are marked, a question mark means to run this command separately on each file.

In a slightly more complex example, you might have a command with more than one file as an argument. For example, you might want to make a new file out of the sorted phone list.

Move the cursor to the phone file, then type: !


Emacs asks what command you want to run (Mac OS X).

Now tell Emacs you want to sort your phone file and put the output in a new file called phonesorted. The cursor is on the phone file, so you don't need to type its name in the command. Substitute an asterisk (*) for the name of the file:

Type: sort * > phonesorted


The operating system sorts the phone file and puts the output into the new file phonesorted (Mac OS X).

We created the file, but it doesn't appear on the display, which is not automatically updated in this case. To see the phonesorted file, type g.

Type: g


Emacs updates the Dired display, showing the file phonesorted (Mac OS X).

Dired is frankly inconsistent about whether you type g before the display is updated. Some commands, as we'll see shortly, update the display immediately. Others, such as running shell commands on files, do not (Emacs really doesn't know what shell commands it's running or their effect on the display). A good rule of thumb is to type g if you don't see what you expect to see.


: 0.314. /Cache: 3 / 1