gpt4 book ai didi

awk - 替换子字符串中的引号(最好没有外部依赖项)

转载 作者:行者123 更新时间:2023-12-05 08:29:43 25 4
gpt4 key购买 nike

我正在尝试通过将引号 (") 替换为 \" 或空字符串来清理文本文件中的引号。替换必须发生在由 TOKEN 占位符分隔的子字符串中。

例子

# input (example.txt):
Line title "A" - TOKEN some line with "quotation marks"
Line title "B" - TOKEN some line with "another quotation marks"
Line title "C" - TOKEN some "line" TOKEN more "text"
Random "line"


# result (example.txt)
Line title "A" - TOKEN some line with \"quotation marks\"
Line title "B" - TOKEN some line with \"another quotation marks\"
Line title "C" - TOKEN some \"line\" TOKEN more "text"
Random "line"


# Another option
# result (example.txt)
Line title "A" - TOKEN some line with quotation marks
Line title "B" - TOKEN some line with another quotation marks
Line title "C" - TOKEN some line TOKEN more "text"
Random "line"

最好在 Linux 上没有外部依赖项(即 Python、JS),所以可能 sed、awk、bash 是最好的

PS - 到目前为止我尝试过的是:

sed -iE "s/TOKEN(.+)(\")(.+).*\TOKEN\1\3/g" /tmp/test

但它每行只处理一次替换

编辑:(很抱歉在很多答案后添加延迟)

  • TOKEN 是一个定界符 - 在示例中添加了行标题“C”
  • 在没有 token 的情况下不应在线进行替换 - 添加随机“行”

最佳答案

假设:

  1. 您希望将 TOKEN 视为正则表达式(否则将在使用它之前转义元字符),
  2. 没有出现TOKEN的行应该保持不变,并且
  3. TOKEN 匹配,即使它在另一个字符串的中间也是如此

然后在每个 Unix 机器上的任何 shell 中使用任何 awk:

$ awk '
match($0,/TOKEN.*TOKEN/) || match($0,/TOKEN.*/) {
tgt = substr($0,RSTART,RLENGTH)
gsub(/"/, "\\\"", tgt)
$0 = substr($0,1,RSTART-1) tgt substr($0,RSTART+RLENGTH)
}
1' example.txt
Line title "A" - TOKEN some line with \"quotation marks\"
Line title "B" - TOKEN some line with \"another quotation marks\"
Line title "C" - TOKEN some \"line\" TOKEN more "text"
Random "line"

关于awk - 替换子字符串中的引号(最好没有外部依赖项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68527081/

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