如何用sed用模式替换文件中的行?

Hen*_*ley 33 linux bash regex sed command-line

我正在阅读大量有关 sed 的文档,但仍然对我的特定用例感到困惑。

我想用我自己的行替换 conf 文件中的这一行:

替换这一行:

#maxmemory <字节>
和:
最大内存 26GB

这是我尝试过的:

sed s/maxmemory.*bytes.*/maxmemory 26gb//etc/redis/redis.conf

我收到错误:

sed: -e 表达式 #1, char 30: 未终止的 `s' 命令

这让我很难过,因为我不知道这意味着什么。所以我的问题是:

我怎样才能完成我想要的?这个错误是什么意思?(所以我可以从中学习)

小智 38

你忘记了 -i。应进行修改:

$ sed -i 's/maxmemory.*/maxmemory 26gb/' /some/file/some/where.txt


Sxi*_*rik 11

的确

该错误意味着在没有引号的情况下,您的 shell 使用空格来分隔参数。maxmemory和之间的空格26gb因此被视为终止第一个参数,因此/sed将该参数解析为其命令之一时缺少终端。

将正则表达式放在单引号之间,这样您的 shell 就不会将其拆分为多个参数并将其sed作为一个参数传递,从而解决了问题:

$ sed s/maxmemory.*/maxmemory 26gb/ /some/file/some/where.txt
sed: -e expression n°1, caractère 23: commande `s' inachevée
Run Code Online (Sandbox Code Playgroud)

尽管

$ sed 's/maxmemory.*/maxmemory 26gb/' /some/file/some/where.txt
Run Code Online (Sandbox Code Playgroud)

作品。

希望有帮助。