使用sed

时间:2017-07-17 14:44:11

标签: python regex sed

我正在研究一个有很多功能的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执行此操作?此外,必须添加新行的功能可以在任何地方,无需在开头或结尾。

4 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

SED

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

有关:b

的文档,请参阅the manual

我使用边界标记\<\>来避免模式的模糊(即避免匹配def xyz123()

或ed

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

答案 3 :(得分:0)

懒惰的替代答案

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