简体   繁体   English

vim,ed或sed在给定文件上进行多次搜索和替换

[英]vim, ed or sed multiple search and replace on a given file

I want do a series of "search and replace" on a given file, say file.txt. 我想在给定的文件上做一系列的“搜索和替换”,比如file.txt。 For example, 例如,

s/foo/bar/g
s/abc/xyz/g
s/pqr/lmn/
g/string-delete/d 

and so on. 等等。

How shuld I write all these actions in a script file and then run them on a single go on the target file.txt to save it to newfile.txt? 我是如何在脚本文件中编写所有这些操作,然后在目标file.txt上单独运行它们以将其保存到newfile.txt?

I saw this post Search and replace variables in a file using bash/sed but somehow couldn't get it to work for me. 我看到这篇文章使用bash / sed搜索和替换文件中的变量,但不知何故无法让它为我工作。

Edit: i would prefer a vim/ed based solution Thanx tempora 编辑:我更喜欢基于vim / ed的解决方案Thanx tempora

Use :source {file} to run a vim script. 使用:source {file}运行vim脚本。

Save your commands to a file, eg commands.vim . 将命令保存到文件,例如commands.vim Then open up the buffer that you want to apply the commands to and source the commands.vim file like so: 然后打开要应用命令的缓冲区并获取commands.vim文件,如下所示:

:so commands.vim

Note: :so is short for :source 注意:: :so简称:source

For more help see: 有关更多帮助请参阅:

:h :so

You can put the commands in a file and pass it to sed -f : 您可以将命令放在文件中并将其传递给sed -f

$ cat commands.sed↵
s/foo/bar/g
s/abc/xyz/g
s/pqr/lmn/
/string-delete/d
$ sed -f commands.sed my_input.txt > my_output.txt↵

or even make it a shell-script 甚至使它成为shell脚本

$ cat munge.sed↵
#!/bin/sed -f
s/foo/bar/g
s/abc/xyz/g
s/pqr/lmn/
/string-delete/d
$ chmod a+x commands.sed↵
$ ./munge.sed my_input.txt > my_output.txt↵

Finally, you can pass the commands directly to sed(1) as a one-liner: 最后,您可以将命令直接传递给sed(1)作为一行:

$ sed -e "s/foo/bar/g" -e "s/abc/xyz/g" -e "s/pqr/lmn/" -e "/string-delete/d" my_input.txt > my_output.txt↵

You could just write a function wrap those commands, and call the function. 您可以编写一个函数来包装这些命令,然后调用该函数。

Note !! 注意 !!

the function below is an example, I added % in front of your s cmd. 下面的函数是一个例子,我在你s cmd前添加了% because I guess you want to do substitution on whole buffer, not on "current" line. 因为我猜你想在整个缓冲区上进行替换,而不是在“当前”线上。 But you have to be careful, in this way, the previous replaced result could be replaced again by latter command, if the latter pattern matched. 但是你必须要小心,这样,如果后一个模式匹配,之前的替换结果可以被后一个命令再次替换。 just adjust it as your needs. 只需根据您的需要进行调整。

eg think about: 想想:

text: fooc you have %s/foo/ab/g and %s/abc/def/g text: fooc你有%s/foo/ab/g%s/abc/def/g

fun! ExecThem()
    %s/foo/bar/g
    %s/abc/xyz/g
    %s/pqr/lmn/g
    g/string-delete/d
endf

source the function, then 然后来源于该功能

:call ExecThem()

will do the job. 会做的。

you could of course create a command for that: 你当然可以为此创建一个命令:

command Mybatch call ExecThem()

一种简单快捷的方法是将命令复制到一个带有"ay的寄存器中,然后使用@a将寄存器作为运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM