簡體   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