Linux: Execute previous command and replace program name

Sometimes you execute a command and need to execute it again by changing the program called e.g.

cat /etc/hosts
vi /etc/hosts

Of course you can just use the arrow up to get back to the previous line, press CTRL-A to get to the beginning of the line, delete three characters and right vi instead of cat. But there is a better way to do it. You can just execute the previous command and use a search and replace:

cat /etc/hosts

It will replace cat by vi and execute the following:

vi /etc/hosts

You can do the same thing by executing the following:


If all you replace is the command used, you can also do it this way:

vi !!:*

It will execute vi with all arguments used for the previous command.

If what you’re after is only the last argument of the previous command, you can also use the Alt-. keyboard shortcut. This will take the last argument of the previous command and print it to the command line. So you can write vi and press Alt-. (Alt-Dot) and you will get “vi /etc/hosts”. If you had the following in the previous command:

cat /etc/hosts /etc/hosts.allow

You’d get:

vi /etc/hosts.allow

All this is also useful if you typed a long command line and misspelled something e.g. cta instead of cat.

One thought on “Linux: Execute previous command and replace program name

Leave a Reply

Your email address will not be published.