How to access the second argument from the last command in the history ?

I am starting to learn some Regex, therefore I use this command repeatedly:

grep pattern /usr/share/dict/american-english 

Only the part with pattern changes, so I have to write the long expression “/usr/share/dict/american-english” again and again.

Someone made the remark that it is possible to expand an argument of a command from the command history by typing cryptic character combinations instead of the full expression.
Could you tell me those cryptic character combinations ?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can use <M-.> (or <Esc>. if your Meta key is being used for something else), that is, Meta-dot (or <esc> dot), where Meta is usually the Alt key, to recall the last argument of the previous command. So, first you would type

$ grep foo /usr/share/dict/american-english

And then if you wanted to grep for something else, you would type

$ grep bar

After typing a space and then Esc. (that is, first pressing the escape key, and then the period key):

$ grep bar /usr/share/dict/american-english

You can also use either of the following:

$ grep bar !:2
$ grep bar !$

Where !:2 and !$ mean “second argument” and “last argument” respectively.

Solution 2

In general (with Bash) <Esc> N <Esc> . will recall the N’th argument from the previous command into the current command line (where N is 0-based).

For the second argument from the last command, that would be:

<Esc> 1 <Esc> .

If you wanted the third argument, then

<Esc> 2 <Esc> .

… and so on.

As others have mentioned, if you want the last argument from the previous command, there’s a specific shortcut for that in just:

<Esc> .

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply