【问题标题】:Insert multiple lines between a pattern at some specific position using sed使用 sed 在某个特定位置的模式之间插入多行
【发布时间】:2017-12-22 03:59:49
【问题描述】:

我正在开发一个具有这么多功能的 python 模块。我想在某个特定位置的特定函数中插入几行。假设这是代码:

def abc():

    #few lines of code
    context =  {}
    return context

def xyz():

    #few lines of code
    context = {}
    return context  

现在我想在上下文之前添加“这是新行”,但仅在函数 xyz 中:

def abc():

    #few lines of code
    context =  {}
    return context

def xyz():

    #few lines of code
    This is new line
    context = {}
    return context 

如何使用 sed 做到这一点?此外,必须添加新行的功能可以在任何地方,不必在开头或结尾。

【问题讨论】:

  • 如果可以使用 Python,为什么还要“使用 sed”? 8-)
  • @Blotosmetek 实际上我正在创建一个可以应用于该 python 模块的任何版本的补丁

标签: python regex sed


【解决方案1】:

试试这个:

sed '/^def xyz/,/^[[:space:]]*context/{s/^\([[:space:]]*\)context/\1This is new line\n&/;}' file

说明:

  • /^def xyz/,: 从def xyz 开始的行
  • /^[[:space:]]*context/:最多以空格(或制表符)开头的行,后跟context
  • s/^\([[:space:]]*\)context/\1This is new line\n&/;:用捕获的空格替换空格/制表符和context,然后是新字符串,然后是换行符(\n

【讨论】:

  • 您能解释一下吗?我是 sed 的新手
  • 我编辑了我的答案。如果你想了解更多关于sed的知识,我推荐这个优秀的Introduction and tutorial
  • “This is new line”如何遵循与上下文相同的缩进?
  • context 之前的空格/制表符用\([[:space:]]*\) 捕获,并用\1(反向引用)在替换字符串中输出。
【解决方案2】:

您可以使用awk 来完成这项工作:

输入文件:

cat file
def abc():

    #few lines of code
    context =  {}
    return context

def xyz():

    #few lines of code
    context = {}
    return context

def pqr():

    #few lines of code
    context =  {}
    return context

这里是 awk:

awk '/^def /{fnflag = index($0, " xyz()")}
    fnflag && /context = /{print "    This is new line"} 1' file
def abc():

    #few lines of code
    context =  {}
    return context

def xyz():

    #few lines of code
    This is new line
    context = {}
    return context

def pqr():

    #few lines of code
    context =  {}
    return context

【讨论】:

  • 感谢您的努力,但由于某些原因我不得不使用 sed
  • 你可能会在这里得到一些复杂的 sed 脚本,但最重要的是 sed 是这个工作的错误工具。
  • 好的,我也会研究一下 awk。谢谢
【解决方案3】:

sed

sed -i '
    /def xyz\>/ {
        :A
        n
        /\<context\>/ {
            i\
    This is a new line
            bB
        }
        bA
    }
    :B
' file

有关 :b 的文档,请参阅 the manual

我使用单词边界标记\&lt;\&gt; 来避免模式的歧义(即避免匹配def xyz123()

或编辑

ed file <<'END'
/def xyz\>
/\<context\>
i
    This is a new line
.
wq
END

【讨论】:

  • 鉴于这一切,我会改用awk
【解决方案4】:

已接受答案的懒惰替代方法

sed  '/^def xyz/,/^def/ s/.*context =.*/   This is a new line\n&/'

【讨论】:

    猜你喜欢
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2013-04-18
    • 2015-03-05
    • 1970-01-01
    相关资源
    最近更新 更多