从终端历史记录中搜索和替换命令

时间:2022-09-12 23:05:53

I would like to know how/if I can reuse a command from my terminal history, but in a modified version. Here's an example:

我想知道如何/如果我可以重用我的终端历史记录中的命令,但是在修改后的版本中。这是一个例子:

$ filter_script file2 > output_file2
$ # ...
# now run the same command, but replace '2' with '4'
$ filter_script file4 > output_file4

This is a very simple example, and of course I can simply access the command from the history and manually replace the two 2s, but is there a more elegant way?

这是一个非常简单的例子,当然我可以简单地从历史记录中访问命令并手动替换这两个2,但是有更优雅的方式吗?

Thanks a lot for your time!

非常感谢你的时间!

1 个解决方案

#1


12  

If there's only one instance of whatever it is you want replaced, bash(1) has an easy feature first introduced in csh(1):

如果你想要替换的只有一个实例,bash(1)有一个在csh(1)中首先引入的简单特性:

^old^new

will replace the first instance of old with new:

将用new取代旧的第一个实例:

$ filter_script file2 > output_file2
$ ^2^4
filter_script file4 > output_file2

If you want to replace all the instances, that requires more typing:

如果要替换所有实例,则需要更多输入:

$ filter_script file2 > output_file2
$ !:gs/2/4/
filter_script file4 > output_file4

The g specifies the global replacement on the command line. The ! refers to a line from history -- which could be more specific, if you wanted to pull a command from further back in history that the immediately previous command. See bash(1)'s section on Event Designators.

g指定命令行上的全局替换。的!指的是历史记录中的一行 - 如果您想在历史记录中进一步返回上一个命令,则可能更具体。请参阅bash(1)关于事件指示符的部分。

#1


12  

If there's only one instance of whatever it is you want replaced, bash(1) has an easy feature first introduced in csh(1):

如果你想要替换的只有一个实例,bash(1)有一个在csh(1)中首先引入的简单特性:

^old^new

will replace the first instance of old with new:

将用new取代旧的第一个实例:

$ filter_script file2 > output_file2
$ ^2^4
filter_script file4 > output_file2

If you want to replace all the instances, that requires more typing:

如果要替换所有实例,则需要更多输入:

$ filter_script file2 > output_file2
$ !:gs/2/4/
filter_script file4 > output_file4

The g specifies the global replacement on the command line. The ! refers to a line from history -- which could be more specific, if you wanted to pull a command from further back in history that the immediately previous command. See bash(1)'s section on Event Designators.

g指定命令行上的全局替换。的!指的是历史记录中的一行 - 如果您想在历史记录中进一步返回上一个命令,则可能更具体。请参阅bash(1)关于事件指示符的部分。