tags:

views:

66

answers:

3

I have to replace all ocurrences of: 5.6xx and 5.5xx (where x is a 0-9 digit) on a textfile with 5.500, but only when the line that contains the match starts with a string (e.g. STARTSTRING). That 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 can I do this. I am using sed for the editing.

Thanks a lot! :)

PS: If necessary, I am running the latest debian version.

A: 
sed -i -e '/^STARTSTRING/s/5\.[56][0-9]{2}/5.500/g' $file
wich
Yours doesn't do what the OP asked for.
Dennis Williamson
Indeed, misread it, focused only on the matching only certain lines, fixed
wich
+3  A: 
sed -i -e '/^STARTSTRING/s/5\.[56][0-9][0-9]/5.500/g' file
Carl Norum
This was exactly what I was looking for. Thanks a lot :)
Pablo Hevia-Koch
No problem. Good luck!
Carl Norum
maybe you should put a boundary in case numbers like 35.530 shows up and you don't want to to change that.
ghostdog74
Sure, stick a space in before the `5\.` and the other `5.`.
Carl Norum
+1  A: 

you can use awk as well

$ 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 the sed solutions doesn't take care of numbers like 35.530.

ghostdog74