regex - sed:匹配两行并插入一行
问题描述
我有一个css文件:
@font-face {
font-family: "Roboto";
src: local(Roboto Thin), url("../fonts/roboto/Roboto-Thin.woff2") format("woff2"), url("../fonts/roboto/Roboto-Thin.woff") format("woff");
font-weight: 100; }
仅当匹配 font-face 行和 font-family 行时,我才想添加一行:
@font-face {
font-family: "Roboto";
font-display: swap;
src: local(Roboto Thin), url("../fonts/roboto/Roboto-Thin.woff2") format("woff2"), url("../fonts/roboto/Roboto-Thin.woff") format("woff");
font-weight: 100; }
我试过这样的东西,但它给了我一个错误,不匹配的'{'
sed '/\@font-face/{N;/ font-family\: \"Roboto\"\;/a \ \ font-display\: swap\;}' style.css > test.txt
有什么帮助吗?
解决方案
您可以使用
sed -e '/@font-face/{' -e n -e '/font-family: "Roboto"/a \ \ font-display: swap;' -e '}' style.css > test.txt
见在线sed
演示:
s='@font-face {
font-family: "Roboto";
src: local(Roboto Thin), url("../fonts/roboto/Roboto-Thin.woff2") format("woff2"), url("../fonts/roboto/Roboto-Thin.woff") format("woff");
font-weight: 100; }'
sed -e '/@font-face/{' -e n -e '/font-family: "Roboto"/a \ \ font-display: swap;' -e '}' <<< "$s"
输出:
@font-face {
font-family: "Roboto";
font-display: swap;
src: local(Roboto Thin), url("../fonts/roboto/Roboto-Thin.woff2") format("woff2"), url("../fonts/roboto/Roboto-Thin.woff") format("woff");
font-weight: 100; }
细节
'/@font-face/{'
- 找到一行@font-face
,开始一个块n
- 清除模式空间,将下一行读入其中'/font-family: "Roboto"/a \ \ font-display: swap;'
- 如果当前模式空间(带有 的行正下方的行@font-face
)包含 `font-family: "Roboto",则附加该行font-display: swap;
'}'
- 块结束。
推荐阅读
- laravel - Laravel 8 共享主机中缺少混合清单文件
- php - 我们可以在管理中使用 API 来管理这些数据吗?
- algorithm - 有多少种方法可以实现贝尔曼福特算法?
- android - 与 RecyclerView 的数据绑定未正确呈现
- python - getresponse() 将元组作为字符串返回
- c++ - 与频率的最小 Levenshtein 距离
- python-3.x - 如何清除随机生成的数据以在循环中的每个文件中创建新数据?
- python - 如何在 mac book pro 上设置 python3 的路径?
- c - 如何在C中的循环中包含最后一个元素?
- php - 取消按钮在函数 alert_remove() 中不起作用