将文本添加到由 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/

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
@-

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

sed '/^~s*$/{:a;n;/^~~s*$/b;n;//b;s/^/== /;ba}' file

在每首诗的第二行之前插入==,其中诗歌由~~~分隔。

sed 用于对单个字符串执行s/old/new仅此而已。对于 sed 来说,这是一个完全不合适的任务,对于 awk 来说绝对是微不足道的,而且正是创建 awk 要执行的任务类型,您无需向文本添加额外的~分隔符即可从您发布的第一个输入块获取您发布的输出:

$ awk -v RS= -F'n' '{for (i=1; i<=NF; i++) print (i%2?"":"==") $i; print ""}' file
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

以上将在每个 UNIX 机器上使用任何 shell 中的任何 awk。

相关内容

最新更新