首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从awk结果中替换字符串?

如何从awk结果中替换字符串?
EN

Server Fault用户
提问于 2014-11-14 14:49:45
回答 1查看 696关注 0票数 1

我有一个包含replaceme多次出现的JSON文件。

我只想根据上面几行找到的一个特定字符串来替换一个事件。

例如,

代码语言:javascript
复制
[...]
    "title" : {
      "Propertie1" : "xxxx",
      "Propertie2: "replaceme"
    }

    "title2" : {
      "Propertie1" : "xxxx",
      "Propertie2: "replaceme"
    }
    "title" : {
      "Propertie1" : "xxxx",
      "Propertie2: "replaceme"
    }

    "title2" : {
      "Propertie1" : "xxxx",
      "Propertie2: "replaceme"
    }
[...]

在本例中,我只想用replaceme代替title2

使用awk 'title2/,/replaceme/' myFile,我能够找到JSON文件的一部分。我是否也需要执行sed命令,但我不知道如何执行,或者是否可能以这种方式执行?

EN

回答 1

Server Fault用户

回答已采纳

发布于 2014-11-14 19:34:14

代码语言:javascript
复制
[vagrant@localhost ~]$ sed -e '/"title2/,/}/{ s/replaceme/title2/; }' test
    "title" : {
      "Propertie1" : "xxxx",
      "Propertie2: "replaceme"
    }

    "title2" : {
      "Propertie1" : "xxxx",
      "Propertie2: "title2"
    }

    "title" : {
      "Propertie1" : "xxxx",
      "Propertie2: "replaceme"
    }

    "title2" : {
      "Propertie1" : "xxxx",
      "Propertie2: "title2"
    }

https://stackoverflow.com/questions/268045/multi-line-search-and-replace-tool

http://sed.sourceforge.net/sedfaq4.html#s4.23.3

代码语言:javascript
复制
4.24. How do I address all the lines between RE1 and RE2, excluding the lines themselves?

Normally, to address the lines between two regular expressions, RE1 and RE2, one would do this: '/RE1/,/RE2/{commands;}'. Excluding those lines takes an extra step. To put 2 arrows before each line between RE1 and RE2, except for those lines:

     sed '1,/RE1/!{ /RE2/,/RE1/!s/^/>>/; }' input.fil

The preceding script, though short, may be difficult to follow. It also requires that /RE1/ cannot occur on the first line of the input file. The following script, though it's not a one-liner, is easier to read and it permits /RE1/ to appear on the first line:

     # sed script to replace all lines between /RE1/ and /RE2/,
     # without matching /RE1/ or /RE2/
     /RE1/,/RE2/{
       /RE1/b
       /RE2/b
       s/^/>>/
     }
     #---end of script---

Contents of input.fil: Output of sed script:
      aaa                           aaa
      bbb                           bbb
      RE1                           RE1
      aaa                           >>aaa
      bbb                           >>bbb
      ccc                           >>ccc
      RE2                           RE2
      end                           end
票数 1
EN
页面原文内容由Server Fault提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://serverfault.com/questions/644375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档