views:

329

answers:

5

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:

  • I need to match from the end, not from the start
  • the substring that I want to scan for is fixed, not variable.
A: 

I would look up the man pages for awk or sed.

epochwolf
A: 

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.

MrTelly
+3  A: 
  • for truncating at the start: ${var#pattern}
  • truncating at the end ${var%pattern}
  • ${var/pattern/repl} for general replacement

the 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.

Javier
A: 

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.

Shannon Nelson
A: 

Hi there

Usually when I get stuck with Sed I use this page,

http://sed.sourceforge.net/sed1line.txt