Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh: Expand a previous argument in the current command line

I find myself often wanting to do simple commands like:

cp /really/long/path/from/file.txt /really/long/path/to/file.txt

Although I already use shortcuts like !! and !$ often, it would be nice to be able to reference the last argument in the current command line (and optionally expand it for editing). Is there a way to do this in zsh, or some other equivalent trick to save time?

like image 783
robbles Avatar asked Feb 02 '13 00:02

robbles


2 Answers

In general, you can refer to individual words in the current command line using history expansion.

$ cp /really/long/path/from/file.txt !#:1:s/from/to

or

$ cp /really/long/path/from/file.txt !#:$:s/from/to

The !# is history expansion for the command line typed so far. :1 specifies the first argument in that expansion (in ths case, the long file path). :$ could be used instead to refer to the last argument, independent of how many arguments have been typed so far. :s/from/to performs text substitution on the selected word.

For this task, you can also use brace expansion:

$ cp /really/long/path/{from,to}/file.txt

(Note: both of these are taken from bash, but also work in zsh. There may be other zsh-only tricks that I am not aware of.)

like image 50
chepner Avatar answered Oct 17 '22 19:10

chepner


You can hit Tab to expand stuff on zsh. For example:

If I do this command first

% ls /etc 

And in this next line I do

% !!<Tab>

The !! will be replaced with

% ls /etc

So I can edit this the way I want. This works for a lot of things like * and Environment variables. For example tapping the Tab key after $TERM, will replace (expand it) with (for example in my case) xterm-256color

like image 35
lmcanavals Avatar answered Oct 17 '22 19:10

lmcanavals