7

I usually use csh (actually my /bin/csh is linked to tcsh, an improved version of csh) and frequently use !$ to refer to the last argument of the last command.
But sometimes I would like to use the last two arguments of the previous command. How can I do that? and I guess I could access the arguments of any previous commands.

I have read How can I recall the argument of the previous bash command? but couldn't find the answer. How can we refer to the second to last argument of the previous command?

For example, If I gave echo tiger rabbit, how can I refer tiger for the following command? An answer for csh would be best but I'm curious about the bash case too.

Chan Kim
  • 5,177
  • 12
  • 57
  • 112
  • What is the command for doing a global substitution of string "x" for string "y" in the previous command and then executing it. I've been able to substitute the first occurrence of the string but not all of them. $> ls DF DF $> ^DF^DA^ ls DA DF When I would really like to transform "ls DF DF" into "ls DA DA" with a single substitution. Tcsh solutions preferred but bash also works. Thank you! – user3014653 Dec 07 '21 at 17:41

1 Answers1

14

Using history expansion you can pick a specific command from the history, execute it as it is, or modify it and execute it based on your needs. The ! starts the history expansion.

  • !! Repeats the previous command
  • !10 Repeat the 10th command from the history
  • !-2 Repeat the 2nd command (from the last) from the history
  • !string Repeat the command that starts with “string” from the history
  • !?string Repeat the command that contains the word “string” from the history
  • ^str1^str2^ Substitute str1 in the previous command with str2 and execute it
  • !!:$ Gets the last argument from the previous command.
  • !string:n Gets the nth argument from the command that starts with “string” from the history.

  • !^ first argument of the previous command

  • !$ last argument of the previous command
  • !* all arguments of the previous command
  • !:2 second argument of the previous command
  • !:2-3 second to third arguments of the previous command
  • !:2-$ second to last arguments of the previous command
  • !:2* second to last arguments of the previous command
  • !:2- second to next to last arguments of the previous command
  • !:0 the command itself

Last but not least, I would also recommend you to press on Alt + . to access to the last argument of any of the previous commands you have entered

Allan
  • 12,117
  • 3
  • 27
  • 51
  • 1
    Wow, thanks I remember seeing some of them but this is the complete list! – Chan Kim Nov 10 '17 at 12:13
  • can we substitute all occurrences of a pattern in the previous command into new one? For example if I typed `ls DA DA`, how can I run `ls DE DE` by substituting DA to DE in the previous command? `^DA^DE^` substitutes only the first one making `ls DE DA`. – Chan Kim Dec 08 '21 at 01:01