I have a file containing a set of information as below: cat filename    1   S121    2   M121    3   MS121    4   SM154    5   SM91 I am trying to change only all of those which has [mM] to MS plus keeping the same pattern. The following sed script was tried sed -r 's/ms?([0-9])/MS\1/Ig' filenamebut it is not specific only to [mM] and can change the lines 4 and 5 as in the output as below: 4       SMS1545       SMS91any help is appreciated. tnx! 
How to use appropriate regex to find a pattern in sed?
linux;text processing;command line;sed
You are matching a substring, starting with m, optionally followed by s, and then followed by a digit [0-9].The text on lines 4,5 does contain this substring too:4   SM1545   SM91 so they are replaced.Try prefixing your pattern with \s to indicate that you are only interested in the prefix of column #2, like that:sed -r 's/(\s)ms?([0-9])/\1XX\2/Ig'