简体   繁体   中英

How to edit a file saved in string using sed?

I need to edit the file saved in a string using sed. As per the below example, I want to change some pattern in the php.ini file. Below example will allow only to change what is saved in the string.

[root@server ~]# PHPINI=/etc/php.ini
[root@server ~]# sed "s/somepattern/changedpattern/" <<< "$PHPINI"

Can somebody help? Thanks in advance.

You're using the herestring syntax which passes a string on standard input. You should instead pass the name of the file as an argument:

sed 's/somepattern/changedpattern/' /etc/php.ini

To overwrite the existing file, the standard method is to write to a temporary file and then overwrite the original:

sed 's/somepattern/changedpattern/' /etc/php.ini > tmp && mv tmp /etc/php.ini

Some versions of sed support "in-place" editing (which does more or less the same in the background):

sed -i.bak 's/somepattern/changedpattern/' /etc/php.ini

This creates a backup of the original file with a .bak suffix.

If the filename is contained within a variable, then simply use that instead

php_ini=/etc/php.ini
sed -i.bak 's/somepattern/changedpattern/' "$php_ini"

Note my use of lowercase variable names. Uppercase ones should be reserved for use by the shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM