您可以使用bash脚本中包含的正则表达式编辑.html文件吗?
以下是我要做的事情:
replaceText="<a href="some-file-here" id="text">link to the new file</a>"
#open index.html file stream(how?)
#do some if condition that meets the regex below:
IF index.html contains <td abbr="fileOne">(.*)</td>
Index.html replaceText
我对bash脚本很新,但我想知道上述内容是否可行?
这必须适用于osx unix和linux。
这是index.html示例:
<html>
<head>
</head>
<body style="width: 50%; height: 50%;">
<div style="top: 10%; left: 10%; position: absolute;">
<img border="0" src=“icon.png” alt="Hello World" width="120" height="120">
<table style="width:300px">
<tr>
<td abbr=“file one”><a href=“someFile” id="text">Install file one here…</a></td>
<td abbr=“fileTwo”><a href=“someFileTwo” id="text">install file Two here…</a></td>
<td></td>
</tr>
</table>
</div>
</body>
</html>
提前致谢
编辑:我尝试使用sed命令
sed -i.bak 's/<td abbr="fileOne">(.*?)<\/td>/WHAT_YOU_WANT/' index.html
但是当我打开.bak文件时出现上述错误:
syntax error near unexpected token `newline'
答案 0 :(得分:2)
您可以使用sed
命令执行此操作。
如果您要替换<td abbr="fileOne">(.*)</td>
,可以使用以下内容:
sed 's/<td abbr=[“"]fileOne["”]>(.*?)<\/td>/WHAT_YOU_WANT/'
这里有一个有效的例子:
<强> Working demo 强>
您需要将-i
选项传递给sed
以进行内联更改,并在原始文件进行更改之前创建原始文件的备份:
sed -i.bak -E 's/<td abbr=["”]fileOne["”]>(.*?)<\/td>/WHAT_YOU_WANT/' index.html
如果您不想使用斜杠作为分隔符,可以将其更改为#
(并且您也不必使用#跳过斜杠):
sed -i.bak -E 's#<td abbr=["”]fileTwo["”]>(.*)?</td>#WHAT_YOU_WANT#' index.html
答案 1 :(得分:1)
如果你想测试一个文件中是否有某个模式可用,然后运行一些其他脚本,如果是这种情况你可以测试grep的输出,我会包括这个完整性的答案&#39;缘故。
if [ $(grep -c '<td abbr="fileOne">(.*?)<\/td>' index.html) -ne 0 ]
then
some_func_you_want_to_run #this is the case where the line is present
else
exit 1 #this is the case where it isn't
fi
exit 0
值得注意的是regex's are not a good fix for parsing html但是因为我希望你所做的只是替换一行,所以使用sed如上所述将是最好的方法。如果您确实有更严格的需求,我建议使用ruby,python或perl等脚本语言以及像ruby这样的hok解析器,例如nokogiri。