Using sed to replace beginning of line when match found

Capture the whole line that contains myvar:

$ sed 's/\(^.*myvar.*$\)/\/\/\1/' file

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

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

Use the -i option to save the changes in the file sed -i 's/\(^.*myvar.*$\)/\/\/\1/' file.

Explanation:

(      # Start a capture group
^      # Matches the start of the line 
.*     # Matches anything 
myvar  # Matches the literal word 
.*     # Matches anything
$      # Matches the end of the line
)      # End capture group 

So this looks at the whole line and if myvar is found the results in stored in the first capture group, referred to a \1. So we replace the whole line \1 with the whole line preceded by 2 forward slashes //\1 of course the forwardslashes need escaping as not to confused sed so \/\/\1 also note that brackets need escaping unless you use the extended regex option of sed.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)