首页 > 解决方案 > 将文本添加到由 sed 中的某些特殊字符定义的特定块

问题描述

我有数百本文本格式的书籍,将使用 pandoc 将其转换为 epub 和 pdf。每个文本文件都包含纯文本和诗歌。对齐诗歌是一项重复的任务。每首诗的每一第二行都需要有针对性。我需要在每首诗的每隔一行添加一些特殊字符,例如,==

我的问题是:

here are some text  

poem line 1  
poem line 2  
poem line 3  
poem line 4  

here are some text

poem line 1  
poem line 2  

我需要输出

here are some text  

poem line 1  
==poem line 2  

here are some text  

poem line 1  
==poem line 2  
poem line 3  
==poem line 4  

我的想法是:

如果我们用一些特殊字符来定义诗歌块,比如

~   
poem line 1  
poem line 2  
~~  

~  
poem line 1  
poem line 2  
poem line 3  
poem line 4  
~~  

sed 找到这个~==在每 3+2 行添加并以~~.

输出应该是这样的

~   
poem line 1  
== poem line 2  
~~  

~  
poem line 1  
== poem line 2  
poem line 3  
== poem line 4  
~~  

是否可以使用 sed 或 awk 或任何其他脚本?

http://xensoft.com/use-sed-to-insert-text-every-n-lines-characters/

标签: awksed

解决方案


sed '/^$/b;n;/^$/b;s/^/--/' input
  • /^$/b:如果该行为空,则打印它并从下一行重新开始。
  • n: 打印当前行并获取下一行。
  • s/^/--/:在行中添加特殊字符。

输出:

here are some text  

poem line 1  
--poem line 2  
poem line 3  
--poem line 4  

here are some text

poem line 1  
--poem line 2 

您可以按照建议使用分隔符:

here are some text
@+
poem line 1  
poem line 2  
poem line 3  
poem line 4  
@-
here are some text
@+
poem line 1  
poem line 2 
poem line 3
@-

使用此命令:

sed '/@+/!b;:l;n;/@-/b;n;/@-/b;s/^/--/;bl;' input

你得到:

here are some text
@+
poem line 1  
--poem line 2  
poem line 3  
--poem line 4  
@-
here are some text
@+
poem line 1  
--poem line 2 
poem line 3
@-

推荐阅读