Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed to replace beginning of line when match found

Tags:

regex

sed

I have a Java file. I want to comment any line of code that contains the match:

 myvar 

I think sed should help me out here

 sed 's/myVar/not_sure_what_to_put_here/g' MyFile.java 

I don't know what to put in:

not_sure_what_to_put_here 

as in this case, I don't want to replace myVar but the I want to insert

// 

to the beginning of any line myVar occurs on.

Any tips

like image 599
dublintech Avatar asked Jan 03 '13 10:01

dublintech


People also ask

How do you use sed to replace the first occurrence in a file?

With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.

How do you find and replace a line using sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do you use sed on a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.


1 Answers

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.

like image 193
Chris Seymour Avatar answered Oct 06 '22 00:10

Chris Seymour