Search code examples
bashshellsedawktextutils

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:

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

Solution

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