使用 Grep 进行多次查找和替换

Mic*_*cki 0 command-line html grep web-development 15.04

我有 90 个 HTML 文件,我必须将一个新的 JS 脚本链接放到每个文件的头部部分。现在,我可以使用一些代码编译器的一些 F&R 引擎

喜欢:

find: </head>
replace it with: link to JS script</head>
Run Code Online (Sandbox Code Playgroud)

但我不喜欢这个解决方案,因为在那之后代码很混乱。

我想知道 - 如何使用 grep 在特定目录中的所有 .html 文件中的标记之前插入新的脚本链接?

Joh*_*024 6

grep不替换或修改文件。使用sed

sed -i 's|</head>|link to JS script</head>|' *.html
Run Code Online (Sandbox Code Playgroud)

这个怎么运作

-i 告诉 sed 就地修改文件。

最重要的sed命令是替换。它的形式为s|old|new|whereold是正则表达式。在这里,我们替换</head>link to JS script</head>

*.html 告诉 sed 对 shell 在当前目录中找到的所有 html 文件进行操作。