9

我使用 zsh 和 emacs 键绑定。有时我需要使用不同的输入执行相同的命令。输入通常具有公共子字符串。有没有一种简单的方法可以用其他字符串替换先前命令的一部分?例如,前面的命令是:

cat chr2.unknow.feature.filtered ../chr2.unknow.feature.filtered ../train/chr2.unknow.withpvalue.feature.filtered > chr2.combined.txt

我怎样才能轻松地将“chr2”替换为“chr3”?

问题的扩展,如何将命令中的几个不同的子字符串替换为其他不同的字符串:

cat chr1.unknow.feature.filtered ../chr2.unknow.feature.filtered ../train/chr3.unknow.withpvalue.feature.filtered

比如说,如何用“chrX”替换“chr1”,用“chrY”替换“chr2”,用“chrZ”替换“chr3”?

谢谢。

4

2 回答 2

20

您还可以使用(比 快得多)进行快速历史替换^old^new!!:s^old^new^

~ % cd /tmp
/tmp % ^tmp^etc  # <-- changes tmp for etc
/tmp % cd /etc
/etc % 

这只会改变第一次出现。如果您需要更多,请使用任何历史修饰符。示例:全局更改:

/etc % echo tmp tmp tmp
tmp tmp tmp
/etc % ^tmp^etc
/etc % echo etc tmp tmp  # <--- only the first tmp got changed
etc tmp tmp
/etc % ^tmp^etc^:G       # <-- 'global'

PS:搜索zshexpn手册^foo^bar以找到描述此的部分。向下滚动一点(在手册中),您将看到“历史扩展修改器”列表。

PS:对于多个替换,做:^old1^new1^:s^old2^new2^

于 2013-04-26T14:48:31.757 回答
9

要直接完成您的要求:

$ !!:s/chr1/chrX/:s/chr2/chrY/:s/chr3/chrZ/

这将修改最后输入的命令。要执行全局替换,请使用:gs/a/b/.

例子:

$ man zshall
$ !!:gs/man/less/:gs/zshall/.history/<TAB>
$ less .history

阅读更多man zshexpn内容——ZSH 扩展和替换。

于 2013-04-26T08:43:42.127 回答