首页 > 解决方案 > 如何使用 sed 命令将 = 之后的值替换为 null

问题描述

我有一个场景,我想在不创建新文件的情况下替换digit or string等于=null [空白] 需要在同一个文件中替换

文件中的数据:

name=vilas
age=21
code=1345

需要替换后的code=1345数字code=

我试过这个但卡住了

sed -i 's/^code=$/code=/1g' file.txt

注意: code= 之后的值将是动态的,需要使用我不擅长的正则表达式模式匹配

标签: linuxunixawksed

解决方案


根据您的问题:

在 MacOS 和 FreeBSD 上

sed -i '' -E 's/^code=[[:digit:]]+$/code=/g' test1.txt

在 CentOS 和 Debian 上

sed -i -E 's/^code=[[:digit:]]+$/code=/g' test1.txt

您可以更新字符类以满足您的需要。

在哪里

-i  Edit files in-place
-E  Interpret regular expressions as extended (modern) regular expressions rather than basic regular expressions (BRE's).
s   The substitute command
g   Apply the replacement to all matches to the regexp, not just the first.

GNU 文档:https : //www.gnu.org/software/sed/manual/html_node/Character-Classes-and-Bracket-Expressions.html SED 文档:https ://www.gnu.org/software/sed/manual /sed.html


推荐阅读