gpt4 book ai didi

regex - awk中的多个字段分隔符单引号 ' '和双引号 ""

转载 作者:行者123 更新时间:2023-12-01 22:30:56 25 4
gpt4 key购买 nike

我之前曾要求打印两个连续“”内的文本。例如我有以下字符串:

gfdg "jkfgh" "jkfd fdgj fd-" ghjhgj
gfggf "kfdjfdgfhbg" "fhfghg" jhgj
jhfjhg "dfgdf" fgf
fgfdg "dfj jfdg jhfgjd" "hfgdh jfdhgd jkfghfd" hgjghj

我只想打印以下内容:

"jkfgh" "jkfd fdgj fd-"
"kfdjfdgfhbg" "fhfghg"
"dfgdf"
"dfj jfdg jhfgjd" "hfgdh jfdhgd jkfghfd"

我得到了使用这个命令的答案:

awk -F'"' '{for (i=2;i<5;i+=2) printf "%s%s%s%s", FS, $i, FS, (i>5-2?"\n":" ")}' sample.txt

现在我必须将 ' ' 添加到我的问题中。即我的文本可以在 ' ' 以及 "" 中。下面的例子:

gfdg "jkfgh" "jkfd fdgj fd-" ghjhgj
gfggf "kfdjfdgfhbg" "fhfghg" jhgj
jhfjhg "dfgdf 'ffdg' gfd" "dgffd 'fdg'"fgf
fgfdg 'dfj "jfdg" jhfgjd' 'hfgdh jfdhgd jkfghfd' hgjghj

我想得到以下结果:

"jkfgh" "jkfd fdgj fd-"
"kfdjfdgfhbg" "fhfghg"
"dfgdf 'ffdg' gfd" "dgffd 'fdg'"
'dfj "jfdg" jhfgjd' 'hfgdh jfdhgd jkfghfd'

有人可以帮帮我吗?

最佳答案

{
a = ""
s = $0
# while s contains a delimiter (either " or ')
while (match(s, /['"]/)) {
# save the delimiter
c = substr(s, RSTART, 1)
# remove up to and including the delimiter
s = substr(s, RSTART + 1)
# find the matching delimiter
i = index(s, c)
# append the saved delimiter and the first segment of s to the accumulator
a = a " " c substr(s, 1, i)
# remove the segment
s = substr(s, i + 1)
}
# print the accumulator (dropping the first space)
print substr(a, 2)
}

关于regex - awk中的多个字段分隔符单引号 ' '和双引号 "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29559774/

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