Replace string2 with string3 on all lines starting with string1

My OS is Windows 10 and I am using Cygwin.

The file 1 content is:

USE solution 2; -4.000
USE solution 3; -4.000

USE solution 29; -4.000
USE solution 30; -4.000
USE solution 31; -4.000
�.
USE solution 89; -4.000
...
USE solution 202; -4.000
etc...

I need to replace string2(-4.000) with string3(-2.000) on all lines starting with string1(USE solution 2, USE solution 3, �USE solution 29) but the other lines don't have to be changed.

I wrote the following script which does it, but only for the first line:

sed '/^USE solution 2/ { s,-4.000,-2.000, }' file1.txt > file2.txt

I am looking for a way to use this sed function in a loop where I could say:

If USE solution i (i=2 to 29), then do the replacement.

Being a newbie, I don't have experience at all with loops, sorry for that.

Thanks in advance.

GNU sed - the one that comes with linux can handle this. When you ask a question it is a good idea to tell us the UNIX OS you have, at a minimum.

To uese extended regex (ERE) choose the sed -r option. And use alternation:

# On linux or cygwin:
 sed -r '/^USE solution ([2-9]{1}|[1][0-9]|2[0-9])/ { s,-4.000,-2.000, }'  file1.txt > file2.txt

Sample run:

$ cat file1.txt
USE solution 2; -4.000
USE solution 3; -4.000
USE solution 29; -4.000
USE solution 30; -5.000
USE solution 31; -5.000

Owner@Owner-PC ~
$ sed -r '/^USE solution ([2-9]{1}|[1][0-9]|2[0-9])/ { s,-4.000,-2.000, }'  file1.txt
USE solution 2; -2.000
USE solution 3; -2.000
USE solution 29; -2.000
USE solution 30; -5.000
USE solution 31; -5.000

Thanks.

But your script does the replacement for all the lines and not only for those beginning with USE solution 2 to USE solution 29.

Try this adaptation of Jim's suggestion:

sed -r '/^USE solution ([2-9]|[12][0-9]);/ { s,-4.000,-2.000, }'  file1.txt > file2.txt
2 Likes

Thanks. This works.

But how can adapt this script to apply it for e.g. lines 74 to 93?

For lines 74 to 93? Or lines containing USE solution 74; till ... 93; ?

I meant for lines containing USE solution 74 till USE solution 93

Then adapt the regex to sth. like 7[4-9]|8[0-9]|9[0-3] .

1 Like

Thanks, works perfectly!