gpt4 book ai didi

bash - 用 "` `"and "''"替换引号

转载 作者:行者123 更新时间:2023-11-29 09:35:51 25 4
gpt4 key购买 nike

我有一个包含许多 " 标记的文档,但我想将其转换为在 TeX 中使用。

TeX 使用 2 个 ` 标记作为开始引号,2 个 ' 标记作为结束引号。

我只想在 " 以偶数出现在单行上时对这些进行更改(例如,有 2、4 或 6 个 " 在线)。例如

"This line has 2 quotation marks."
--> ``This line has 2 quotation marks.''

"This line," said the spider, "Has 4 quotation marks."
--> ``This line,'' said the spider, ``Has 4 quotation marks.''

"This line," said the spider, must have a problem, because there are 3 quotation marks."
--> (unchanged)

我的句子从不跨行,所以不需要检查多行。

有几个单引号,所以我可以手动更改它们。

我如何转换这些?

最佳答案

这是我的单线,适合我:

awk -F\" '{if((NF-1)%2==0){res=$0;for(i=1;i<NF;i++){to="``";if(i%2==0){to="'\'\''"}res=gensub("\"", to, 1, res)};print res}else{print}}' input.txt >output.txt

还有这个带有注释的单行本的长版本:

{
FS="\"" # set field separator to double quote
if ((NF-1) % 2 == 0) { # if count of double quotes in line are even number
res = $0 # save original line to res variable
for (i = 1; i < NF; i++) { # for each double quote
to = "``" # replace current occurency of double quote by ``
if (i % 2 == 0) { # if its closes quote replace by ''
to = "''"
}
# replace " by to in res and save result to res
res = gensub("\"", to, 1, res)
}
print res # print resulted line
} else {
print # print original line when nothing to change
}
}

您可以通过以下方式运行此脚本:

awk -f replace-quotes.awk input.txt >output.txt

关于bash - 用 "` `"and "''"替换引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967033/

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