gpt4 book ai didi

regex - Bash 中的多个多行正则表达式匹配

转载 作者:行者123 更新时间:2023-11-29 09:13:38 26 4
gpt4 key购买 nike

我正在尝试在 bash 脚本中进行一些相当简单的字符串解析。基本上,我有一个由多个多行 字段组成的文件。每个字段都被已知的页眉和页脚包围。

我想将每个字段分别提取到一个数组或类似的数组中,就像这样

>FILE=`cat file`
>REGEX="@#@#@#[\s\S]+?@#@#@"
>
>if [[$FILE =~ $REGEX ]] then
> echo $BASH_REMATCH
>fi

文件:

@#@#@#################################
this is field one
@#@#@#
@#@#@#################################
this is field two
they can be any number of lines
@#@#@#

现在我很确定问题是 bash 不匹配带有“.”的换行符

我可以用“pcregrep -M”匹配这个,当然整个文件都会匹配。我可以一次从 pcregrep 获得一场比赛吗?

我不反对使用一些内联 perl 或类似的东西。

最佳答案

如果你有gawk

awk 'BEGIN{ RS="@#*#" }
NF{
gsub("\n"," ") #remove this is you want to retain new lines
print "-->"$0
# put to array
arr[++d]=$0
} ' file

输出

$ ./shell.sh
--> this is field one
--> this is field two they can be any number of lines

关于regex - Bash 中的多个多行正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2118121/

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