Coder10
Coder10

Reputation: 65

Finding and replacing within file

Goal: Write script to find all instances of the statement "x=x+1" and it should change it to "x++"

My idea: I would use a for loop to go through each line in the file. Then I would use the sed command to replace every instance of "x=x+1" with "x++"

for line in filename do
sed -i /s/"*=*+1"/replacement/g

I am having trouble trying to figure out how to turn this into proper code.

Upvotes: 0

Views: 73

Answers (2)

ErlVolton
ErlVolton

Reputation: 6784

You can use sed's in-place parameter (-i or --in-place):

sed -i 's/x=x+1/x++/g' someFile.c

Which will produce equivalent results and be more efficient than:

sed 's/x=x+1/x++/g' someFile.c > someFileNew.c; mv someFileNew.c someFile.c

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19733

test.txt contains
x=x+1
age=age+1

this code will do wt you want:

sed -i 's/\(.*\)=.*+1$/\1++/g' text.txt

Upvotes: 1

Related Questions