awk - 将文本添加到由 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
@-
推荐阅读
- javascript - 我的不和谐机器人有某种角色错误
- javascript - Javascript:body.append(content) 未呈现为 html
- java - 从 RealtimeDatabase 读取特定节点
- github - 如何更新 github 上组织的每个存储库的给定文件中的版权年份?
- javascript - 如何在线获取word文档的正确lastSaveTime值
- java - 为 Web 服务忽略自动装配的构造函数
- python - python模式检测和替换字符串
- android-studio - 无法将我的客户端应用程序连接到 ejabberd 本地服务器
- xamarin - 无法将 Castle.Proxies.INavigationServiceProxy 类型的对象转换为 Prism.Common.IPageaware
- sql - 我无法在 d3 中可视化数据