2014-07-01 38 views
-1

嗨有可能使用包含在bash脚本中的正则表达式来编辑.html文件吗?使用正则表达式使用批处理脚本编辑index.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

你是指批处理脚本还是bash脚本?你说你想让你的解决方案在osx unix和linux上工作,但批处理文件只能用于Windows? –

+0

对不起bash脚本。必须在unix/linux – jonney

+1

上使用sed,POSIX兼容sed在所有这些系统上都可用,请参阅答案。 (假设你想替换与你的replace_text相匹配的行,这是问题似乎在问) –

回答

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 
+0

Cheers,sed如何打开并与index.html文件进行交互? – jonney

+1

sed's/(。*?)<\/td>/WHAT_YOU_WANT /'index.html> index.html – CKK

+0

嗨,我试过这个例子,它只是抹去index.html的内容 – jonney

1

测试一个文件中是否存在某种特定的模式,然后运行其他脚本(如果可以测试grep的输出的话),为了完整性,我会包含这个答案。

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之类的脚本语言,以及诸如nokogiri之类的html解析器。