替换正则表达式中的嵌套反向引用

问题描述 投票:1回答:2

我从Excel电子表格中提取了一列,其中一些单元格包含多行,有些则不包含。多行单元格由引号分隔。我想用“,”替换那些多行单元格中的返回值。所以我的文件看起来像这样:

"Alpha
 Beta
 Gamma"
 123
 456
"Apple
 Banana
 Cherry"
 789
 this is a single-line cell

我的目标是

 Alpha, Beta, Gamma
 123
 456
 Apple, Banana, Cherry
 789
 this is a single-line cell

我可以编写一个使用嵌套模式捕获那些多行单元格的模式,但我不知道如何“到达内部”以获得反向引用。

"(([^"]+)\n)+([^"]+)"
regex grep nested pcre
2个回答
0
投票

尝试:

$ sed '/^"/{:a; /"$/bb; N; ba; :b; s/\n//g}' file
"Alpha Beta Gamma"
 123
 456
"Apple Banana Cherry"
 789
 this is a single-line cell

How it works

  • /^"/{...} 对于以"开头的任何行,将执行花括号中的命令。
  • :a 这会创建一个标签a
  • /"$/bb 如果当前模式空间以"结尾,则跳转到标签b
  • N 在模式空间中读取一个新行。
  • ba 分支回到标签a
  • :b 这定义了标签b
  • s/\n//g 从模式空间中删除任何换行符。

0
投票

使用GNU awk进行多字符RS和RT:

$ awk -v RS='"[^"]+"|[^"\n]+' '$0=RT{gsub(/^\s+|\s+$|"/,""); gsub(/\n/,","); print}' file
Alpha, Beta, Gamma
123
456
Apple, Banana, Cherry
789
this is a single-line cell
© www.soinside.com 2019 - 2024. All rights reserved.