我有数百本文本格式的图书,这些图书将通过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/
答案 0 :(得分:0)
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
@-
答案 1 :(得分:0)
这可能对您有用(GNU sed):
sed '/^~\s*$/{:a;n;/^~~\s*$/b;n;//b;s/^/== /;ba}' file
在每首诗歌的第二行之前插入==
,其中诗歌用~
和~~
分隔。
答案 2 :(得分:0)
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进行工作。