一次只能使用大量.txt文件替换有限次数

时间:2013-01-22 23:21:47

标签: text

我有很多包含文字的.txt文件。在文中有一些符号,让我们说“@”。它们出现在随机位置。我想用另外2个符号替换这些符号中的前2个符号。所以,如果我有“@@ ... @ ... @@”(有......是文本),我想把它变成这样:xx ... @ ... @@(如果我想要更换@ by x)。 我只想替换前两个符号,但我只遇到了允许我一次替换所有内容或根本不替换所有内容的选项(如此规模)。是否有任何程序或功能允许我一次使用大量文件,换句话说,我不必手动为每个文件执行此操作?

1 个答案:

答案 0 :(得分:-1)

您可以在Vim编辑器中执行此操作。首先,这是如何在一个文件中完成的。假设我们在缓冲区中有这个文件。

junk
@@@@
@@@@

以下命令用@替换文件中x的第一次出现。要做两次,我们只执行两次:

:0/@/s/@/x/

如果我们得到它后执行它:

junk
x@@@
@@@@

然后如果我们再次执行它:

junk
xx@@
@@@@

解剖:

  start search at 0 (before first line)
 | search for something
 || search for a line containing @
 |||  when you find @ perform a substitution command 
 ||| |  replace this
 ||| | |   with that (just once: the first occurrence in the line)
 ||| | |  |
 vvv v v  v
:0/@/s/@/x/
 ^

要在大量文件上运行此命令,我们可以使用脚本自动执行此操作,例如:

 # find all the .txt files here and in all subdirectories,
 # and execute the command "ex <file> < script" on them

 $ find . -name '*.txt' -exec ex {} < script \;

我们使用ex命令作为vi的替代名称,以ex模式启动它,该模式接受标准输入上的ex命令。

script fille包含:

0/@/s/@/x/
0/@/s/@/x/
x

即。执行其中两个替换,然后:x保存并退出。

vi中使用的冒号不是必需的,因为冒号是vi交互式命令模式中用于输入ex命令的命令。