【问题标题】:Replace 2 lines in a file using sed command使用 sed 命令替换文件中的 2 行
【发布时间】:2015-09-16 15:29:04
【问题描述】:

我尝试删除倒数第二行的逗号:

{
  "subject" : {
    "value" : "http://d-nb.info/gnd/1-2",
    "type" : "uri"
    },
  "predicate" : {
    "value" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
    "type" : "uri"
    },
  "object" : {
    "value" : "http://d-nb.info/standards/elementset/gnd#SeriesOfConferenceOrEvent",
    "type" : "uri"
    }
  },
{

我正在使用这个命令:

<test2.file sed '/^\s*\},$/ { N; s/^\s*\},\n\{/^\s*\}\n\{/ }' 

我希望输出应该是这样的:

{
  "subject" : {
    "value" : "http://d-nb.info/gnd/1-2",
    "type" : "uri"
    },
  "predicate" : {
    "value" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
    "type" : "uri"
    },
  "object" : {
    "value" : "http://d-nb.info/standards/elementset/gnd#SeriesOfConferenceOrEvent",
    "type" : "uri"
    }
  }
{

但它返回一个错误。

sed: -e 表达式 #1, char 42: 不匹配 {

有人知道它有什么问题吗?谢谢。

P.S.,这里是文件的结尾:

{
  "subject" : {
    "value" : "http://d-nb.info/gnd/1060867974",
    "type" : "uri"
    },
  "predicate" : {
    "value" : "http://d-nb.info/standards/elementset/gnd#preferredNameEntityForThePerson",
    "type" : "uri"
    },
  "object" : {
    "value" : "_:genid12768016",
    "type" : "bnode"
    }
  }

【问题讨论】:

    标签: regex bash sed


    【解决方案1】:

    不要在您的模式/地址部分转义 { or }。 sed 默认使用 BRE。使用 BRE,{ ( + .. 这样的字符没有特殊含义,您必须将它们转义才能赋予它们特殊含义。

    在您的情况下,您希望匹配文字 { or },然后不要转义它们。

    编辑

    我猜你想删除最后一个逗号,以便更改:

    ...
     },
    {
    

    进入

    ...
     }
    {
    

    那你可以试试:

    awk -v RS='\0' '7+gsub(/,\s*{/,"\n{")' file
    

    用你的文件测试:

    kent$  awk -v RS='\0' '7+gsub(/,\s*{/,"\n{")' f
    {
      "subject" : {
        "value" : "http://d-nb.info/gnd/1-2",
        "type" : "uri"
        },
      "predicate" : {
        "value" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
        "type" : "uri"
        },
      "object" : {
        "value" : "http://d-nb.info/standards/elementset/gnd#SeriesOfConferenceOrEvent",
        "type" : "uri"
        }
      }
    {
    

    【讨论】:

    • 谢谢,现在我改成了:
    • @hui 你能把你想要的输出粘贴过来让我给你做个测试吗?
    • 当然。 {“主题”:{“价值”:“d-nb.info/gnd/1-2”,“类型”:“uri”},“谓词”:{“价值”:“w3.org/1999/02/22-rdf-syntax-ns#type”,“类型”:“uri”},“对象" : { "值" : "d-nb.info/standards/elementset/gnd#SeriesOfConferenceOrEvent", "类型" : "uri" } } {
    • @hui 我的意思是将您的问题粘贴到代码块中,以便人们阅读。不在评论中。 ;-)
    • @hui 我在答案中添加了 awk 单行,检查它是否是你想要的。
    【解决方案2】:

    您可以使用缩进来识别正确的行吗?

    sed 's/^ },/ }/'

    【讨论】:

    • 答案中的命令对我有用,当我将您提供的示例复制粘贴到运行 sed 时。
    猜你喜欢
    • 2013-09-25
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2014-12-28
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多