【问题标题】:How to remove a comma 2nd to the last line of the file using SED?如何使用 SED 删除文件最后一行的第二个逗号?
【发布时间】:2022-12-05 07:32:57
【问题描述】:

我正在尝试使用 sed 在第二行到最后一行搜索并删除逗号 ,

这就是我现在所拥有的:

}
   "user-account-id": "John",
   "user-account-number": "v1001",
   "user-account-app": "v10.0.0",
   "user-account-dbase": "v10.1.0",
}

我希望最终结果是这样的:

}
   "user-account-id": "John",
   "user-account-number": "v1001",
   "user-account-app": "v10.0.0",
   "user-account-dbase": "v10.1.0"
}

我以为我在发布此消息后一个小时就找到了答案,但我错了。它没有用。

试运行这些组合中的任何一个都不起作用:

sed '2,$ s/,$//' filename
sed '2,$ s/,//' filename
sed '2,$ s/,//g' filename
sed '2,$s/,$//' filename
sed '2,$s/,//' filename
sed '2,$s/,//g' filename

使用这些组合中的任何一个进行实际删除都不起作用:

sed -i '2,$ s/,$//' filename
sed -i '2,$ s/,//' filename
sed -i '2,$ s/,//g' filename
sed -i '2,$s/,$//' filename
sed -i '2,$s/,//' filename
sed -i '2,$s/,//g' filename

我认为使用 '2,$ 运行 sed 只会修改文件中的“第二行到最后一行”。

输出只会删除每一行中的逗号,这是没有意义的:

}
   "user-account-id": "John"
   "user-account-number": "v1001"
   "user-account-app": "v10.0.0"
   "user-account-dbase": "v10.1.0"
}

【问题讨论】:

    标签: bash shell sed


    【解决方案1】:

    2,$ 是一个范围从开头的第二行开始到最后一行结束(所以除了第一行之外的所有行)。在sed 中修改倒数第二行很难,请参见例如Replace the "pattern" on second-to-last line of a file

    但就您而言,GNU sed 有一个更简单的解决方案:

    将整个文件视为一个字符串并删除最后一个逗号(如果它后跟任何空格,甚至是换行符和 })。

    sed -Ez 's/,([ 	
    ]*)}([ 	
    ]*)$/}/' file
    

    如果你知道最后

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 2016-08-17
      • 2016-11-24
      • 1970-01-01
      • 2014-01-25
      相关资源
      最近更新 更多