1

I am trying to match bla = 0.05 and replace the number with 1234 in a file. Expected output is bla = 1234

Code I tried:

sed -i '' "s/\(bla\)\(.*\)\([-+]?[0-9]*\.?[0-9]*\)/#\1\21234/g" foo

Also, why do I sometimes need '' and sometimes not to call sed ?

Sundeep
  • 19,273
  • 2
  • 19
  • 42
Tuni
  • 99
  • 1
  • 8
  • 1
    see https://stackoverflow.com/questions/5694228/sed-in-place-flag-that-works-both-on-mac-bsd-and-linux for usage of `-i` between different versions of sed... – Sundeep Oct 22 '16 at 15:55
  • for the problem you are trying to solve, can you add more sample inputs with expected output for clarity? one issue apparent is that you need to use `\?` instead of `?` – Sundeep Oct 22 '16 at 15:58
  • also, `.*` would consume too much... `sed -i '' 's/\(bla\)\([^0-9+-]*\)\([-+]\?[0-9]*\.\?[0-9]*\)/#\1\21234/g' foo` might help – Sundeep Oct 22 '16 at 16:01
  • sorry thats the only input i have for this problem – Tuni Oct 22 '16 at 16:03
  • ok, what is expected output? – Sundeep Oct 22 '16 at 16:04
  • bla = 1234 is the expected output – Tuni Oct 22 '16 at 16:09

1 Answers1

1
$ echo 'bla = 0.05' > foo
$ cat foo 
bla = 0.05
$ sed 's/\(bla[^0-9.+-]*\)\([-+]\?[0-9]*\.\?[0-9]*\)/\11234/g' foo
bla = 1234


If extended regex option is available, either -E or -r

$ sed -E 's/(bla[^0-9.+-]*)([-+]?[0-9]*\.?[0-9]*)/\11234/g' foo
bla = 1234


See sed in-place flag for requirements of using -i flag between different sed versions

Community
  • 1
  • 1
Sundeep
  • 19,273
  • 2
  • 19
  • 42
  • the -E command worked. THank you very much. Im trying to figure out why my version did not work – Tuni Oct 22 '16 at 16:40
  • 1
    because `.*` is [greedy](https://stackoverflow.com/documentation/regex/429/greedy-and-lazy-patterns#t=201610221644401303712) and every pattern after that can be `0` or more... for example, try this simpler command for experimenting... `echo 'bla = 0.05' | sed 's/\(bla\)\(.*\)[0-9]*/\2/'` – Sundeep Oct 22 '16 at 16:44
  • 1
    also `echo 'bla = 0.05' | sed 's/bla\(.*\)\([0-9]*\)/\1 abc \2/'` – Sundeep Oct 22 '16 at 16:46
  • i understand. If i want to match 'foo is left' whilst the string left could also be right, can i do it like this ?: 'sed -E -i '' "s/(foo[^[left]|^[right]]*)([left]|[right])/\1$ContSide/g" bar' – Tuni Oct 22 '16 at 17:17
  • 1
    @Thunfisch not sure about that, would highly recommend you to go through this: https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean – Sundeep Oct 23 '16 at 02:50