Reputation: 3051
I am writing a shell (bash) script and I'm trying to figure out an easy way to accomplish a simple task.
I have some string in a variable. I don't know if this is relevant, but it can contain spaces, newlines, because actually this string is the content of a whole text file.
I want to replace the last occurence of a certain substring with something else. Perhaps I could use a regexp for that, but there are two moments that confuse me:
Upvotes: 1
Views: 1030
Reputation:
Usually when I get stuck with Sed I use this page,
http://sed.sourceforge.net/sed1line.txt
Upvotes: 0
Reputation: 2126
Javier's answer is shell specific and won't work in all shells.
The sed answers that MrTelly and epochwolf alluded to are incomplete and should look something like this:
MyString="stuff ttto be edittted"
NewString=`echo $MyString | sed -e 's/\(.*\)ttt\(.*\)/\1xxx\2/'`
The reason this works without having to use the $ to mark the end is that the first '.*' is greedy and will attempt to gather up as much as possible while allowing the rest of the regular expression to be true.
This sed command should work fine in any shell context used.
Upvotes: 0
Reputation: 62583
${var#pattern}
${var%pattern}
${var/pattern/repl}
for general replacementthe patterns are 'filename' style expansion, and the last one can be prefixed with #
or %
to match only at the start or end (respectively)
it's all in the (long) bash manpage. check the "Parameter Expansion" chapter.
Upvotes: 4
Reputation: 14865
amn expression like this
s/match string here$/new string/
should do the trick - s is for sustitute, / break up the command, and the $ is the end of line marker. You can try this in vi to see if it does what you need.
Upvotes: 1