我有一个用段标记的文件,用 {} 对标识:

{One day}, {the cat said to the owl}, "{Owl}, {would you like to climb the mountain}?"
{The owl replied}, "{Yes}, {I would}."
{So the cat and owl climbed the mountain}.
{The next day}, {they went to the ocean}.

我需要复制所有的行,这样每行只有一个标记的段。带有四个标记段的行将被复制四次,每行仅显示一个标记的段。结果如下所示:
{One day}, the cat said to the owl, "Owl, would you like to climb the mountain?"
One day, {the cat said to the owl}, "Owl, would you like to climb the mountain?"
One day, the cat said to the owl, "{Owl}, would you like to climb the mountain?"
One day, the cat said to the owl, "Owl, {would you like to climb the mountain}?"
{The owl replied}, "Yes, I would."
The owl replied, "{Yes}, I would."
The owl replied, "Yes, {I would}."
{So the cat and owl climbed the mountain}.
{The next day}, they went to the ocean.
The next day, {they went to the ocean}.
  • 大括号从不嵌套。
  • 大括号永远不会跨行拆分。
  • 如果方便的话,我可以用任何其他符号替换 {}

  • 如何重复包含标记段的所有行,以便在 sed 或其他 BASH 工具中的每一行上只出现一个标记段?

    最佳答案

    这可能对你有用(GNU sed):

    sed ':a;/{/!d;s/{[^}]*}/\n&\n/;h;s/[{}]//g;s/\n/{/;s/\n/}/;G;P;s/[^\n]*\n//;s/\n{//;s/}\n//;ba' file
    

    仅打印包含花括号的行(如果要打印这些行,请将 d 替换为 b )。用独特的标记将第一组花括号括起来(换行是一个不错的选择)。复制该行,删除所有花括号,用左花括号替换第一个标记,用右花括号替换第二个标记。附加复制的行。打印第一个修改的行。删除第一行及其换行符。移除第一组花括号并重复。

    沿相同路线的略短版本:
    sed ':a;/{/!d;h;s/{[^}]*}/\n&\n/;s/[{}]//g;s/\n/{/;s/\n/}/p;z;x;s/{//;s/}//;ba' file
    

    关于bash - 如何重复包含标记段的所有行,以便在 BASH 中的每一行上只出现一个标记段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21950517/

    10-16 11:30