regex - 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.
正在覆盖
'
索引.css'
"
索引.css"
- 加上
./
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>
没有输出,也没有替代品。:-(
你能帮我一把吗?
解决方案
试试这个 -
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"
只是一个文字替换字符串。
推荐阅读
- kubernetes - 识别未处于就绪状态的 pod
- c++ - 如何从一些不同的编译时间中选择类型?
- python - 喀拉斯。基本模型的权重设置为“无”,但出现错误
- c - 将指针地址分配给指针的问题
- java - 基于 Android Studio 和 Swing 的应用程序文本/用户界面已损坏
- c# - 在 docker 中构建 dotnet 核心应用程序 - 永远运行
- google-app-engine - 谷歌云平台禁用机器人
- sql - 如何限制 MS-SQl 存储过程的结果
- firebase - 编写 DTO 类来构建从不同数据源获取信息的对象
- c# - 由于应用程序一直挂起,C# 无法将 DataGridView 保存为 png