Linux如何替换星号,其中只有在一定长度的字符串之后



我是Linux命令的新手。最近我得到了一个大字符串文件(4GB) 文件格式如下所示。

1,2,http://*.example.org/
1,3,https://*.example.org/
1,4,https://*.example.org/*
1,5,https://example.org/*example

我想找到并替换仅在行首的每个星号。我想要的结果,例如:

1,2,http://replaced.example.org/
1,3,https://replaced.example.org/
1,4,https://replaced.example.org/*
1,5,https://example.org/*example

我尝试过的内容将替换每次出现的情况。无论如何我能做些什么来获得上面的结果?

sed 's/*/replaced/' inputfile > outputfile

://replaced.://*.您可以使用

sed 's~://*.~://replaced.~' file > newfile

这里

  • ~用作正则表达式分隔符,以避免转义/字符
  • ://*.是子字符串://*.匹配的 POSIX BRE 模式(因为*.是特殊字符,因此它们被转义)

请注意,要匹配字符串开头的星号,您只需要^锚点。因此,要匹配和替换字符串开头的*,您将使用

sed 's/^*/replaced/' file > newfile

但是,您的任何示例文本都不包含任何行首的星号。

如果计划匹配和替换字符串中特定位置的星号,则可以捕获所需长度的子字符串,并替换为对组值和替换文本的反向引用。例如:

sed 's~^(.{11})*~1replaced~' file > newfile

仅当*是字符串中的第 12 个字符时(就像1,2,http://*.example.org/字符串一样),才会替换它。

最新更新