sed pattern matching

Unfortunately this chap has been banned for some reason and I was looking forward to the resolution of his question: -

He was asking if you can use sed to match a pattern you want to replace within a restricted range of characters in a string. Can anyone tell me how to do this?

He wanted to change: -

21111111110001343 000001004OLF-AA029100020091112

to: -

21111111110001343 000001004OLF-1E029100020091112

But I don't want a generic match that matches the whole line, just that range highlighted in blue. Is it possible to do this using sed?

Something like this?

sed 's/.*\(...-..\).*/\1/'

putting tools to use aside, let's think logically. if you want to replace position 28 to 33, then print from position 1 to 27, then print the new replacement, then print from 34 onwards...
pseudocode:

print substr(line,1,27) "OLF-1E" substr(line,34)

no need to think of any regex.

But I like regex :slight_smile:

ssed -r 's/(.{27}).{6}/\1FOO-BR/' infile

Thanks for the replies but I don't think that they quite do what I am asking for. I want to combine the replacement of the characters within the range while matching the pattern.

So the replacement only occurs if the pattern is present within that specific range of characters.

Hi steady, you mean something like this?

sed -r 's/(.{27})OLF-AA/\1OLF-1E/;s/(.{27})ODL-SP/\1ODL-2S/;s/(.{27})ODL-CH/\1ODL-3C/' infile

That's the one, thanks! :slight_smile:

Knew it could be done......