如何在shell命令中交换参数

h7appiyu  于 2023-06-24  发布在  Shell
关注(0)|答案(3)|浏览(85)

我在shell中有一个带参数的命令:

Command -a -b

假设ab是非常长的目录名,它们并不总是第一个和最后一个参数。
但是,我需要再次使用此命令。我使用Ctrl+p返回到上一个命令,但这次我需要颠倒ab的顺序:

Command -b -a

有没有什么方法可以轻松地交换参数,而不是重新输入参数?

7rfyedvj

7rfyedvj1#

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

$ echo foo bar
foo bar
$ !:0 !:2 !:1          # previous command with second arg then first arg
echo bar foo
bar foo
$
6rvt4ljy

6rvt4ljy2#

您可以使用Alt + t来交换当前单词和前一个单词。
Here是更多的快捷键。
请注意,您交换的是单词,而不是参数。例如,如果您混淆了grep的参数顺序,如grep ~/Documents/myFile searchString,并希望将其更正为grep searchString ~/Documents/myFile,Alt + t不会帮助您。
用Paul的答案来代替,并执行!:0 !:2 !:1
如果这对你来说太不方便了(对我来说是这样),你可以在~/.bash_alias中创建一个别名:

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

pieyvz9o3#

2022更新

你可以很容易地剪切和粘贴参数,我经常剪切最后一个参数并将其粘贴到不同的地方。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

相关问题