The main question in Regexp: how to change only lines starting with STRING with sed

I need to replace all the fragments: 5.6xx and 5.5xx (where x is 0-9 digits) in a text file with 5.500, but only when the line containing the match begins with the line (for example, STARTSTRING). It means

STARTSTRING 5.610 4.500 3.550 5.530
OTHERSTRING 5.600 5.500 5.500 5.600

should become

STARTSTRING 5.500 4.500 3.550 5.500
OTHERSTRING 5.600 5.500 5.500 5.600

I am not sure how I can do this. I use sed for editing.

Thank you so much!:)

PS: If necessary, I run the latest version of debian.

+3
source share
3 answers
sed -i -e '/^STARTSTRING/s/5\.[56][0-9][0-9]/5.500/g' file
+3
source

you can also use awk

$ cat file
STARTSTRING 5.610 4.500 3.550 5.530 35.530
OTHERSTRING 5.600 5.500 5.500 5.600 35.500

$ awk '/STARTSTRING/{  for(i=1;i<=NF;i++) if($i ~/^5\.[56][0-9][0-9]/) $i="5.500"} 1 ' file
STARTSTRING 5.500 4.500 3.550 5.500 35.530
OTHERSTRING 5.600 5.500 5.500 5.600 35.500

Note that sed solutions don't care about numbers like 35.530.

+1
source
sed -i -e '/^STARTSTRING/s/5\.[56][0-9]{2}/5.500/g' $file
0

Source: https://habr.com/ru/post/1729938/


All Articles