gpt4 book ai didi

linux - 在 sed 反向引用替换中转义双引号

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:58:36 24 4
gpt4 key购买 nike

我有以下文字:

Matt has 11 eggs and they are brown
Helen has 23 ducks and they are black and brown
Todd has 34 quarters and they are silver
Bud has 45 pens and they are red, yellow, "greenish" and blue

当我运行以下 sed 命令时:

sed -E "s/([^ ]+) has ([^ ]+) ([^ ]+) and they are (.*)/\"\1\",\"\2\",\"\3\",\"\4\"/" input

我得到这个 CSV:

"Matt","11","eggs","brown"
"Helen","23","ducks","black and brown"
"Todd","34","quarters","silver"
"Bud","45","pens","red, yellow, "greenish" and blue"

但我真正想要的是这个(正确转义的引号):

"Matt","11","eggs","brown"
"Helen","23","ducks","black and brown"
"Todd","34","quarters","silver"
"Bud","45","pens","red, yellow, \"greenish\" and blue"

我怎样才能做到这一点?

最佳答案

尝试:

sed -E 's/"/\\"/g; 
s/([^ ]+) has ([^ ]+) ([^ ]+) and they are (.*)/"\1","\2","\3","\4"/' input

这首先用 \" 替换所有 " 实例,然后执行您的原始命令。请注意如何在 sed 程序周围使用引号使其更具可读性。

关于linux - 在 sed 反向引用替换中转义双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23296758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com