Pergunta

I want do a series of "search and replace" on a given file, say 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?

I saw this post Search and replace variables in a file using bash/sed but somehow couldn't get it to work for me.

Edit: i would prefer a vim/ed based solution Thanx tempora

Foi útil?

Solução 3

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. 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.

e.g. think about:

text: fooc you have %s/foo/ab/g and %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()

Outras dicas

Use :source {file} to run a vim script.

Save your commands to a file, e.g. commands.vim. Then open up the buffer that you want to apply the commands to and source the commands.vim file like so:

:so commands.vim

Note: :so is short for :source

For more help see:

:h :so

You can put the commands in a file and pass it to 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

$ 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 -e "s/foo/bar/g" -e "s/abc/xyz/g" -e "s/pqr/lmn/" -e "/string-delete/d" my_input.txt > my_output.txt↵

An easy and quick way would be to copy the commands into a register with "ay and then run the register as a macro with @a.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top