Home > Back-end >  Using sed regex for string replacement
Using sed regex for string replacement

Time:11-13

I am trying to replace a string in the config file. I would like to run something like this:

OS

(docker image php:8.1-apache-buster)

Debian GNU/Linux 10 (buster)

Possible inputs:

post_max_size = 4M
post_max_size = 24M
post_max_size = 248M
...

Example output (any user given value):

post_max_size = 128M

Example cmd:

sed -i 's/(post_max_size = ([0-9]{1,})M/post_max_size = 128M/g' /usr/local/etc/php/php.ini

enter image description here

Joining regex with strings does not work here.

It works when I run string replace without any regex

sed -i 's/post_max_size = 8M/post_max_size = 128M/g' /usr/local/etc/php/php.ini

This works only if the value of the post_max_size is set exactly to 2M. I would like to be able to make a change with regex regardless of the value set.

I searched the Internet and sed cmd docs but did not find anything which fits my use case.

CodePudding user response:

The following should work:

sed -i 's/^post_max_size = .*/post_max_size = 128M/g' /usr/local/etc/php/php.ini

CodePudding user response:

You can use:

sed -i -E 's/(post_max_size = )[0-9] M/\1128M/g' /usr/local/etc/php/php.ini

Or

sed -i 's/\(post_max_size = \)[0-9]\ M/\1128M/g' /usr/local/etc/php/php.ini
  • Related