如何更换一堆文件的多行字符串 [英] How to replace a multi line string in a bunch files

查看:134
本文介绍了如何更换一堆文件的多行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/bin/sh
old="hello"
new="world"
sed -i s/"${old}"/"${new}"/g $(grep "${old}" -rl *)

在preceding脚本只是单行文本工作,我怎么可以编写一个脚本可以代替
多行文本。

The preceding script just work for single line text, how can I write a script can replace a multi line text.

old='line1
line2
line3'

new='newtext1
newtext2'

我可以使用什么命令。

What command can I use.

推荐答案

AWK 可以为你做的。

awk 'BEGIN { RS="" }
  FILENAME==ARGV[1] { s=$0 }
  FILENAME==ARGV[2] { r=$0 }
  FILENAME==ARGV[3] { sub(s,r) ; print }
' FILE_WITH_CONTENTS_OF_OLD FILE_WITH_CONTENTS_OF_NEW ORIGINALFILE > NEWFILE

但你可以用 VIM 做到像这里描述(编写脚本的解决方案)。

But you can do it with vim like described here (scriptable solution).

另请参见并的这个在sed的常见问题。

Also see this and this in the sed faq.

这篇关于如何更换一堆文件的多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆