0

I would like to change the file content which i specified like below.I want to comment out all the lines which contains ".class" except the class name i provide.

@MyClass1.MyClass2(value = {
    Class1.class,
    Class2.class,
    Class3.class,
    Class4.class
})
public class Foo {}

For example if i provide Class2 as parameter to

sed -i -E 's/some_regex/Class2/g'

command,the result should be like this,

@MyClass1.MyClass2(value = {
    //Class1.class,
    Class2.class,
    //Class3.class,
    //Class4.class
})
public class Foo {}

What regex should i use for this?

1

For a file like this:

$ cat file1
@MyClass1.MyClass2(value = {
    Class1.class,
    Class2.class,
    Class3.class,
    Class4.class
})
public class Foo {}
@MyClass11.MyClass2(value = {
    Class1.class,
    Class2.class,
    Class3.class,
    Class4.class
})
public class Foo2 {}

You can have this result:

$ sed '/@MyClass1.MyClass2(*/,/})/{s|\sClass.*|//&|g; /Class2/{s|//||}}' file1
@MyClass1.MyClass2(value = {
   // Class1.class,
    Class2.class,
   // Class3.class,
   // Class4.class
})
public class Foo {}
@MyClass11.MyClass2(value = {
    Class1.class,
    Class2.class,
    Class3.class,
    Class4.class
})
public class Foo2 {}

Explanation:

'/@MyClass1.MyClass2(*/,/})/ {....} --> range to operate in form /from/,/to/{actions}

{s|\sClass.*|//&|g; --> apply // in all lines starting with whitespace \s and then Class

/Class2/{s|//||} --> remove // for Class2

Tip: In sed we can use any char as a separator for s/replacethis/withthat/ synthax.
I choose | to avoid escaping //

  • 1
    I like how you removed the comment from Class2. – unxnut Nov 15 '18 at 20:37
  • Great answer,but i am just wondering, what if i want to apply // in all lines ending with .class? What regex should i use instead of {s|\sClass.*|//&|g; ? – aekber Nov 15 '18 at 21:24
  • @aekber Maybe something like s|\.class$|//&|g. The use of $ is a regex anchor that means "end of line". – George Vasiliou Nov 16 '18 at 7:41
1
awk '/\.class/ && !/Class2/ {print "//", $0}
     !(/\.class/ && !/Class2/) {print $0}' filename
  • I only want to be changed the lines between this annotation @MyClass1.MyClass2(value = {}) – aekber Nov 15 '18 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.