首页 > 解决方案 > 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

有什么帮助吗?

标签: regexawksed

解决方案


您可以使用

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;
  • '}'- 块结束。

推荐阅读