Shell脚本:搜索并替换多行 [英] shell script: search and replace over multiple lines

查看:818
本文介绍了Shell脚本:搜索并替换多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种通过Shell脚本搜索并替换多行的方法.这就是我想要做的:

I'm looking for a way to search and replace over multiple lines through a shell script. This is what I'm trying to do:

source:
[stuff before]
<!--WIERD_SPECIAL_COMMENT_BEGIN-->
  [stuff here, possibly multiple lines.
<!--WIERD_SPECIAL_COMMENT_END-->
[stuff after]    

target:
[stuff before]
[new content]
[stuff after]

简而言之,我想删除注释及其之间的所有内容,并替换为一些新内容.基本上,我想在多行代码上执行一个简单的sed命令,并尽可能使用一些基本的* nix工具,而无需其他脚本语言.

In short, I want to delete the comments and everything between them and replace with some new content. Basically, I want to do a simple sed command over multiple lines, and if possible just using some basic *nix tools, no additional scripting language.

推荐答案

如果只需要匹配完整的行,则可以使用 awk.像这样:

If you only need to match complete lines then you can do this task with awk. Something like:

    awk -v NEWTEXT=foo 'BEGIN{n=0} /COMMENT_BEGIN/ {n=1} {if (n==0) {print $0}} /COMMENT_END/ {print NEWTEXT; n=0}' < myfile.txt

如果文件格式不正确,请在上加上注释 与您要保留或删除的文本相同的行,然后我 将使用perl,将整个文件读取为单个字符串, 执行正则表达式匹配并替换该字符串,然后将新字符串写入 一个新文件.这不是那么简单,您需要编写一个perl脚本来完成工作. 像这样:

If the file is not so well formatted, with comments on the same line as text you want to keep or remove, then I would use perl, read the entire file into a single string, do a regular expression match and replace on that string, then write the new string to a new file. This is not so simple and you need to write a perl script to do the work. Something like:

#!/usr/bin/perl
$newtext = "foo\nbar";
$/ = '';  # no input separator so whole file is read.
$s = <>;  # read whole file from stdin
$startPattern = quotemeta('<!--WIERD_SPECIAL_COMMENT_BEGIN-->');
$endPattern = quotemeta('<!--WIERD_SPECIAL_COMMENT_END-->');
$pattern = $startPattern . '.+' . $endPattern;
$s =~ s/$pattern/$newtext/sg;
print $s;

这篇关于Shell脚本:搜索并替换多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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