繁体   English   中英

sed:匹配两行并插入一行

[英]sed: match two lines and insert a line

我有一个 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"

Output:

@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", append 行font-display: swap;
  • '}' - 块结束。

这可能对您有用(GNU sed):

sed '/@font-face/!b;n;/font-family: "Roboto";/!b;p;s/family.*/display: swap;/' file

如果一行包含@font-face保释,即正常打印。

如果一行确实包含@font-face ,则打印它并将下一个提取到模式空间中,并且它包含font-family: "Roboto"; , bail out 即正常打印。

否则,打印当前行,即font-family: "Roboto"; 然后用display: swap;替换从family到行尾的所有内容;

注意 没有占位符的b命令默认退出所有未来的 sed 命令。 下面的解决方案与上面的结果相同。

sed '/@font-face/!ba;n;/font-family: "Roboto";/!ba;p;s/family.*/display: swap;/;:a' file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM