2017-07-18 21 views
-4

我的Python代碼如下所示:只用在一個特定的塊大括號前添加新線SED

def one(): 
    #lines of code 
    context = { 
     #lines of code 
    } 

def two(): 
    #lines of code 
    context = { 
     #lines of code 
    } 
    context.up({ #lines 
    }) 

我想在結束曲前加入兩個作用範圍內部分「一些新的生產線」大括號如下:

def one(): 
    #lines of code 
    context = { 
     #lines of code 
    } 

def two(): 
    #lines of code 
    context = { 
     #lines of code 
     Some new line 
    } 
    context.up({ #lines 
    }) 

如何使用sed來做到這一點?

我嘗試下面的命令:

sed -i '/^def two.*context={/,/^[[:space:]]}/{s/^\([[:space:]]*\)}/\1some new line\n&/;}' file

,但它似乎並沒有做任何改變。

+0

你想Python或sed的? –

+0

這個問題似乎並不是關於Python的。 – khelwood

+0

@cᴏʟᴅsᴘᴇᴇᴅ我想要使用sed進行此更改。 –

回答

0

這可能爲你工作(GNU SED):

sed '/def two/,/^\s*context\>/!b;/^\s*context\>/!b;:a;n;/^\s*}/!ba;i some new line' file 

範圍限制在def two和內context讀取線高達收盤}並插入一個新行。

第一SED指令是一個正則表達式的範圍即如果線不def twocontext之間打印它們如常,但不與任何SED指令進一步處理它們(b裝置打破任何進一步的命令)。同樣,下一個正則表達式會忽略除包含context之外的所有行。從該地址打印模式空間(PS)中的當前行,並用下一行填充PS(n)。如果該行不包含}跳回(ba)到位置:a。否則,插入(i)一些新文本,然後打印PS的內容。

要保留縮進使用:

sed '/def two/,/^\s*context\b/!b;/^\s*context\b/!b;:a;n;/^\s*}/!h;//!ba;x;s/\S\+.*/some new line with indent/p;g' file 
+0

這不起作用,因爲我也在代碼中使用花括號。所以這個新行在第一次出現大括號之前被添加,但是我希望它在上下文中。 –

+0

@python_user請參閱編輯 – potong

+0

它的工作:)你可以請解釋一下 –