【问题标题】:Adding a String in front of/right after a match via 'sed'通过'sed'在比赛之前/之后添加一个字符串
【发布时间】:2020-05-25 22:05:41
【问题描述】:

我有一堆带有字符串的文件,我想搜索一个特定的匹配项:“exampledata

看起来像这样:

...(...name: Example; age: 21; version: 2131; exampledata: hello;) end

如果在一行中定义了“exampledata”然后什么都不做,否则添加那个字符串exampledata让我们在版本号之后说一个数字(可以是 1 个密码或最多 5-6 个),或者把它放在右括号“)”之前,这始终是字符串中的模式。 (即“Exampledata”就在版本之后和字符串的末尾。后面只有一个“”。)

sed '/exampledata:"/b; /\version.....;\/s/&"exampledata: 2"/'

这是我到目前为止所做的,我不知道如何在版本交互式 bc 之后制作点。在每一行中都可能有一个密码版本或更高的数字。想法?

基本上我正在寻找一个添加“exampledata:2;”的sed命令例如,如果之前根本没有示例数据? (结果是这样的:blabla...(...version: 98; exampledata: 2;)

【问题讨论】:

  • StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
  • 使用!/pattern/command 在任何与模式不匹配的行上执行命令。
  • 该命令应将) 替换为exampledata: 2;)
  • 感谢@Barmar 将问题编辑为我已经解决的问题。将 ) 替换为 exampledata: 2;) 的想法很棒!会用那个
  • version: 2131 周围没有双引号,为什么在模式中有它们?

标签: string bash shell sed


【解决方案1】:

您的模式有双引号,没有出现在数据中。

sed '/exampledata:/!s/version: [0-9]*;/& exampledata: 2;/'

/exampledata:/! 使命令在不包含exampledata: 的行上执行,然后执行更正确的替换。

【讨论】:

  • 这是否需要在末尾添加一个“g”才能使其在全局范围内/通过每一行循环,即使在更正了一个特定行之后也是如此?
  • g 仅用于在一行上进行多次替换。
  • sed 默认循环遍历所有行。
  • 哦,好的,我明白了。我会在明天之前测试你给定的例子并报告。应该像我想象的那样工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多