Wildcards in SED

Hi Folks

Quick one I can't seem to figure out sed wildcards..

I need to replace a string such as "From here.....to here".

I would think the command would look like:
sed 's/From here*to here/new text/g' or
sed 's/From here\*to here/new text/g'

But it's not working for me.

Thanks in advance :slight_smile: :slight_smile:

echo 'aksjfhd from here fooo asdlfkjaslkfjd to here aslfjdlaksjdf' | sed 's/from here.*to here/OVER THERE/'
  • in regular expression will match any number (or none) of the single character that immediately precedes it
sed 's/From here*to here/new text/g'

This regular expression From here*to here will match
From herto here
From hereto here
From hereeto here
...

\ Usually, turn off the special meaning of the following character

sed 's/From here\*to here/new text/g'

This regular expression From here\to here will match
From here
to here

try this

sed 's/From here.*to here/new text/g'

You might want to use the '-r' option to tell sed to use extended regular expressions. Basic sed regexes are quite limited.

Second, regular expressions work differently in sed than they do in a shell. * doesn't mean anything by itself, it's a modifier for something else. First you tell it what expression you want to match, then optionally, how many of them you want to match. An expression can be a single letter, a set of letters, or something in brackets.

  • A by itself just matches the letter A, like you'd expect.
  • [ABC] by itself just matches the letter A, B, or C.
  • A* tells it to match 0 or more A characters.
  • [ABC]* tells it to match 0 or more characters among A, B, C.
  • [A-Z]* tells it to match 0 or more characters among A, B, C, ..., Z.
  • [^A]* tells it to match 0 or more characters that aren't A.
  • (ABC)* tells it to match 0 or more repititions of "ABC".
  • is not the only modifier:
  • A+ tells it to match 1 or more A characters.
  • A? tells it to match 0 or 1 A characters.
  • A{4} tells it to match precisely 4 A characters.

The -r option is not available on all Unix flavour.
AIX sed doesn't support this option.

Jean-Pierre.

Alternative , without regular expression

#!/usr/bin/python
string = "some text in front From here in the middle to here at the end"
fromindex = string.index("From here")
toindex = string.index("to here")
tobeReplace = string[ fromindex : toindex + len("to here") ]
string.replace( tobeReplace , "new text")

Output:

'some text in front new test at the end'