2013-01-03 11 views
0

這與Using sed to replace beginning of line when match found類似,但是有一個不同的問題,所以此線程。需要匹配sed表達式中的兩個組

我希望取消註釋掉註釋掉的代碼。更具體地說,變量myVar被註釋掉的所有情況。

例子:

public class MyClass { 
    ... 
    ... 
    //myVar.setAge(200); 
    //myVar.setPlanet("mars"); 
} 

public class MyClass { 
    ... 
    ... 
    myVar.setAge(200); 
    myVar.setPlanet("mars"); 
} 

正則表達式:

^\\.*myVar.*$ 

獲取我的一切,我需要。

棘手的部分是得到正確的Sed。我嘗試:

sed 's/(^\\)(.*myVar.*$)/\2/g' Build_DM_Digests_Batch.cls 

在以下基礎上。創建兩個匹配組。第一個是註釋掉的線條。其次是線路的其餘部分。用第二個mateched組替換整個行。

這給了錯誤:

sed: -e expression #1, char 29: Unmatched) or \) 

任何提示嗎?

回答

2

使用sed 's/^\(*\)\/\/\(.*myVar.*$\)/\1\2/' file

$ cat hw.java 
class hw { 
    public static void main(String[] args) { 
     System.out.println("Hello World!"); 
//  myVar=1 
     //myVar.setAge(200); 
     //myVar.setPlanet("mars"); 
    } 
} 

$ sed 's/^\(*\)\/\/\(.*myVar.*$\)/\1\2/' hw.java 
class hw { 
    public static void main(String[] args) { 
     System.out.println("Hello World!"); 
     myVar=1 
     myVar.setAge(200); 
     myVar.setPlanet("mars"); 
    } 
} 

使用-i選項保存文件sed -i 's/^\(*\)\/\/\(.*myVar.*$\)/\1/' file的變化:

說明:

^  # Matches the start of the line 
\( # Start first capture group 
*  # Matches zero or more spaces 
\)  # End first capture group 
\/\/ # Matches two forward slashes (escaped) 
\( # Start second capture group 
.*  # Matches anything 
myVar # Matches the literal word 
.*  # Matches anything 
$  # Matches the end of the line 
\)  # End second capture group 

在這裏,我們捕捉到空白高達的//,然後一切之後如果myVar就行並換成\1\2

你的邏輯幾乎是有,但幾件事情,首先躲過所有的括號,其次你要^(*)\/\/^\\這是二逃脫forwardslashes與捕獲的空白不是兩個反斜槓在該行的開頭:

如果你不想逃避括號,你需要使用sed的擴展正則表達式標記-r對於GNU sedOSX它的-E所以檢查sed --help

sed -r 's/^(*)\/\/(.*myVar.*$)/\1\2/' file 

注意:當你匹配的整條生產線(從^$)的g標誌是多餘的。

+0

尋找優秀。你能告訴我爲什麼我們必須在sed中跳過括號而不是grep? – dublintech

+0

'// //'不在OP示例中的行首,所以這不起作用。 – dogbane

+0

@dogbane固定,@ dublintech請參閱編輯括號上的信息。 –

0

另一種方式:

sed 's!^\([ \t]*\)//\(.*\<myVar\>\)!\1\2!' input