51

I want to replace a string with wildcard but it doesn't work.

The string looks like "some-string-8"

I wrote

sed -i 's/string-*/string-0/g' file.txt

but the output is

some-string-08
jww
  • 97,681
  • 90
  • 411
  • 885
mahmood
  • 23,197
  • 49
  • 147
  • 242

2 Answers2

76

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt
tom
  • 21,844
  • 6
  • 43
  • 36
  • well, maybe my question was incomplete.... your command works for this fien. However if I have `some-string-8 -x --command acommand`, the output of executing that command is `some-string-0`. it will delete all characters after that. I want `some-string-0 -x --command acommand` – mahmood Feb 08 '12 at 07:21
  • what if you wish to use the wildcard in the replacement string? example: replace 'AAA.*BBB' with 'CCC.*DDD' – user2561747 Dec 01 '15 at 23:44
  • 4
    turns out it's called back references, wildcards of the form (.*) will get replaced by \1, \2, ... etc. E.g. `sed -r 's/a (.*)cat/the \1bat/g' <<< "a womancat"` yields `the womanbat`. Figured this out from [here](http://stackoverflow.com/questions/15188495/backreferences-in-sed-returning-wrong-value) – user2561747 Dec 02 '15 at 04:05
14

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

Michael Manoochehri
  • 7,931
  • 6
  • 33
  • 47