首页 > 解决方案 > bash 正则表达式替换 html 文件中的 index.css

问题描述

疯了。我需要在大量 html 文件中替换 index.css。所以我正在运行一个 sed (在沙箱中)。

#!/bin/bash
for file in $@
do
  isIndex=$(grep -F "index.css" ${file})
  #isHeader=$(grep -F "</header>" ${file})
  if [ -n "$isIndex" ]; then
    sed -i 's/href=.\.?\/?index\.css./href="..\/assets\/css\/index.css">/' $file
  fi
done

解释

.\.?\/?index\.css.正在覆盖

真正的代码是一组 if-else 语句。这是一个示例文件(为了完整起见,我将所有案例都包含在一个文件中):

<html>
<header>
<link href='index.css' rel='stylesheet'>
<link href="index.css" rel='stylesheet'>
<link href="./index.css" rel='stylesheet'>
</header>
</html>

没有输出,也没有替代品。:-(

你能帮我一把吗?

标签: regexbash

解决方案


试试这个 -

for file in "$@"
do sed -i $'s,href=[\'"][^\'"]*index.css.,href="../assets/css/index.css",g' "$file"
done

您不需要grep读取文件只是为了查看是否sed应该读取文件。sed只会在字符串匹配的地方进行更改,那么为什么要扫描两次呢?

真正的问题是匹配所有引号。:)

cf https://mywiki.wooledge.org/Quotes以获得很好的指导。

详细说明模式$'s,href=[\'"][^\'"]*index.css.,href="../assets/css/index.css",g'

$'...'禁用所有引用,除了其中的反斜杠。

s,,,g设置逗号而不是斜杠作为分隔符,因此我们可以在模式中使用斜杠。

href=[\'"][^\'"]*index.css.作为比赛:

  • [\'"]表示将单引号或双引号匹配为字符类,但由于我们在里面,$'...'我们不希望单引号结束命令字符串,所以我们为命令行解析器引用它。(sed不会看到\'s,所以我在下一段中将它们省略了......)
  • 我们希望['"]后面跟着[^'"]*,这意味着“与不是其中之一一样多的东西”,直到它看到index.css,并且在它之后的一个字符来获取模式假定的内容是结束引号。抓取任何路径信息,[^'"]*例如./等。

href="../assets/css/index.css"只是一个文字替换字符串。


推荐阅读