Suppose I have the following file called Product.java
:
public class Product {
public String name;
public String description;
public String picture;
public double price;
public Product(String name, String description, String picture, double price) {
this.name = name;
this.description = description;
this.picture = picture;
this.price = price;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
public String getPicture() {
return this.picture;
}
public double getPrice() {
return this.price;
}
public String toString() {
return "Product";
}
}
What I am currently trying to do is to replace instances of public
with private
for the class fields only in Product.java
, updating the file in place. So, after replacement, the file should look like:
public class Product {
private String name;
private String description;
private String picture;
private double price;
...
...
...
}
I tried doing this by using sed
with the following statement:
sed -ri 's/public [a-zA-Z a-z]*;/private/' Product.java
However, this just replaces the class fields to just private
. Due to this, I was wondering how do I just replace the public
part of the lines with private
while keeping the rest of the line unchanged? I'm unsure how to accomplish this behavior. Any feedback or suggestions would be greatly appreciated.
sed -ri 's/public ([a-zA-Z a-z]*;)/private \1/' Product.java
\1
to back reference. It is super helpful to know for future reference.