【问题标题】:How to replace the value after = using sed command to null如何使用 sed 命令将 = 之后的值替换为 null
【发布时间】:2021-11-22 11:08:41
【问题描述】:

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

文件中的数据:

name=vilas
age=21
code=1345

需要将code=1345后面的数字替换为code=

我试过了,但是卡住了

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

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

【问题讨论】:

  • sed -i 创建了一个新文件,所以它不满足您的要求。
  • 一般来说,实际上替换文件中的数据是个坏主意。如果你真的想这样做,你可以这样做:sed 's/^code=.*/code=/' file.txt > /tmp/file; cat /tmp/file > file.txt; rm /tmp/filesed -i 可能满足您的实际需求,但它正在创建一个新文件(并将其命名为原始文件的名称),而不是编辑原始文件。

标签: linux unix awk sed


【解决方案1】:
var1=456
$ sed -Ei "s/(code=).*/\1$var1/" file
name=vilas
age=21
code=456

【讨论】:

    【解决方案2】:

    根据您的问题:

    在 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

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多