So I want to take the questions found in sed + add word before string only if not exists and sed -- replace a character in a string when the preceding character is not a certain character and take it a little bit further.
Say I have a file and I want to replace all
\_, but I have two constraints:
_is already preceded by a
\then I don't want anything to happen. (We never get
\\so no need to worry about that case)
- We should only make this replacement if
_appears before two delimiters. For example, between
As an example, the following:
Pretending_we have \_ some start[text that\_is really_cool]end. Then \_nothing_ would start[happen_ to\_ that crew_]end
Would get converted to
Pretending_we have \_ some start[text that\_is really\_cool]end. Then \_nothing_ would start[happen\_ to\_ that crew\_]end
Note: I know that in some cases we'd like to chain sed by replacing every instance of
\_ with something that is not used and then replacing all
\_ and then reversing the first change. But I'd prefer to not do that because I don't know what other characters might be present in the code, so I'd like to do it directly if possible.
Also, I'll be doing this in both vim and terminal (vim as a test run to make sure it's working and then terminal to handle this on 11 different files.) I don't know enough about the differences between the two, but figured I'd mention it in case one is easier than another.
Edit: To answer some questions brought up:
- perl/sed/vim are all acceptable methods to handle the problem. Just not sure what the best approach was and I'm much more comfortable with sed/vim's regex and hence why I mentioned those. (By conflating sed and vim I think I caused confusion so sorry about that. I'm used to using sed and vim regex to handle most of my regex needs, and from what I've noticed usually what I do on one works perfectly on the other. So I'm assuming they're using the same regex handling, but that's probably not a safe assumption I should be making and will look that up. Sorry about the confusion).
- I'm using ubuntu
- Generally the start/end delimiters will be on the same line so theoretically that can be a safe assumption (although if you know how to do it so line doesn't matter, that would be good too for future people looking at a problem like this)