Anonymous
Anonymous

Reputation: 3051

Search and replace in Shell

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

Answers (5)

kmf
kmf

Reputation:

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

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

Upvotes: 0

Shannon Nelson
Shannon Nelson

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

Javier
Javier

Reputation: 62583

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

Upvotes: 4

MrTelly
MrTelly

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

epochwolf
epochwolf

Reputation: 12772

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

Upvotes: 0

Related Questions