^x^y unix 技巧适用于最后一个命令中的所有实例?

Mas*_*son 119 command-line shell bash command-history

我最喜欢的 Unix 技巧之一是^x^y,它将采用最后一个命令并将“x”的第一个实例替换为“y”。但是,我想知道是否有类似的技巧可以在最后一个命令中用“y”替换“x”的所有实例?

slm*_*slm 128

您可以使用该!!:gs/search/replace/符号来做您想做的事。这利用了全局搜索和替换 ( :gs):

$ echo "harm warm swarm barm"
harm warm swarm barm
Run Code Online (Sandbox Code Playgroud)

$ !!:gs/arm/orn/
echo "horn worn sworn born"
horn worn sworn born
Run Code Online (Sandbox Code Playgroud)

参考


Mik*_*kel 60

我不相信有一个简单的方法来添加的东西^string1^string2,使bash更换所有出现。正如 slm 指出的那样,您必须编写!!:gs/string1/string1.

但是zsh,您可以添加:G

$ echo foo foo
foo foo
$ ^foo^bar^:G
echo bar bar
bar bar
Run Code Online (Sandbox Code Playgroud)

bash和 中zsh,您还可以fc -s这样使用:

$ echo foo foo
foo foo
$ fc -s foo=bar
echo bar bar
bar bar
Run Code Online (Sandbox Code Playgroud)

这通常被称为别名,r因此您可以这样做:

$ echo foo foo
foo foo
$ r foo=bar
echo bar bar
bar bar
Run Code Online (Sandbox Code Playgroud)


Art*_*oly 5

我相信最好的选择是使用“:&”

\n
$ echo "dog cat dog"\n$ ^dog^cat^:&\necho "cat cat cat"\ncat cat cat\n
Run Code Online (Sandbox Code Playgroud)\n

但就像下面 St\xc3\xa9phane Chazelas 评论的那样,这仅替换了 2 次出现。如果您有更多,则需要添加更多:&

\n

  • 这取代了 **2** 次出现,而不是*全部*(在本例中是全部,因为只有 2 次出现,但不是一般情况)。您需要添加尽可能多的 `:&`,因为有更多的出现需要替换。 (7认同)