如何在Shell命令中交换参数

Abn*_*hou 8 bash shell command

我在shell中有一个带参数的命令.喜欢

Command -a -b
Run Code Online (Sandbox Code Playgroud)

假设a b是非常长的目录名,并且它们并不总是第一个和最后一个参数.

但是,我需要再次使用此命令.我ctrl+p用来返回命令,但这次我需要逆序a b.

Command -b -a
Run Code Online (Sandbox Code Playgroud)

而不是重新输入它们,有没有办法快速交换它们?

提前致谢.

Pau*_*l R 15

是的,你可以使用历史替换:

$ echo foo bar
foo bar
$ !:0 !:2 !:1          # previous command with second arg then first arg
echo bar foo
bar foo
$ 
Run Code Online (Sandbox Code Playgroud)

  • 如果碰巧要交换第一个和最后一个参数,则可以编写:`!:0!$!^` (2认同)

Mat*_*aun 9

您可以Alt + t用来交换当前和前一个单词.

这里有一些更多的快捷方式.

请注意你交换单词,而不是参数.例如,如果您已经混淆了订单grep将其参数设置为grep ~/Documents/myFile searchString并且想要更正它grep searchString ~/Documents/myFile,Alt + t 则无法帮助您.

转而选择保罗的答案!:0 !:2 !:1.

如果您输入的内容太不方便(对我来说),您可以在以下位置为其创建别名~/.bash_alias:

# Swap the first and the second argument of the last command
alias swapArgs='$(history -p !:0 !:2 !:1)'
Run Code Online (Sandbox Code Playgroud)


dot*_*hen 5

您可以轻松地最后一个 arg剪切并粘贴到不同的位置,而不是交换 args 。Ctrl-W将剪切最后一个参数Ctrl-Y并将其粘贴。

$ # Cursor position is shown as |
$ ls foo bar|

$ # Press <Ctrl-W> to cut the argument just before the cursor
$ ls foo |

$ # Now press <Alt-B> to move the cursor one argument back
$ ls |foo

$ # Now press <Ctrl-Y> to paste the cut argument
$ ls bar|foo

$ # Now press <space> to insert a space between the arguments
$ ls bar |foo

$ # You can safely press <enter> while the cursor is in the middle of the line
$ ls bar |foo
bar foo
Run Code Online (Sandbox Code Playgroud)