简体   繁体   English

如何使用sed编辑保存在字符串中的文件?

[英]How to edit a file saved in string using sed?

I need to edit the file saved in a string using sed. 我需要使用sed编辑保存在字符串中的文件。 As per the below example, I want to change some pattern in the php.ini file. 根据下面的例子,我想在php.ini文件中更改一些模式。 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. 您正在使用herestring语法,该语法在标准输入上传递字符串。 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支持“就地”编辑(在后台或多或少相同):

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

This creates a backup of the original file with a .bak suffix. 这将创建带有.bak后缀的原始文件的备份。

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. 应保留大写的shell以供shell使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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