gpt4 book ai didi

linux - 用于更新链接的 Sed 脚本

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:25:33 25 4
gpt4 key购买 nike

我是 bash 脚本的新手,我写了这个脚本来遍历我网站的所有页面,将索引链接从 .html 更改为 .php .它似乎不起作用。

这是脚本:

#!/bin/bash
FILES=/opt/lampp/htdocs/doLearnFinnace/*
for f in $FILES
do
echo ;

# take action on each file. $f store current file name
if [ -f "$f" ]
then
echo "Processing $f file..."
sed -e 's/"index.html"/"index.php"/g' $f
cat $f
fi
done

最佳答案

脚本中的 sed -e 命令只会在终端上显示替换后的字符串。

您可以使用 -i 选项“就地”(即在文件中)替换字符串:

sed -i 's/"index.html"/"index.php"/g' $f

但是这个命令会替换你代码中的 "index.html",而不是 'index.html'path/index.html

如果你想替换 html 页面中的链接,根据你的链接语法,你可以使用:

sed -i 's/\(href="\/your\/path\/\)index.html"/\1index.php"/g' $f

\/your\/path\/\ 替换为您的真实路径(将 / 转义为 \/)

带有绝对链接的:

sed -i 's/\(href="http:\/\/yourdomain\.com\/your\/path\/\index.html"/\1index.php"/g' $f

此外,要用 find 命令替换 bash 脚本,您可以使用:

find /opt/lampp/htdocs/doLearnFinnace/ -type f -print0 | xargs -0 sed -i 's/\(href="\/your\/path\/\)index.html"/\1index.php"/g'

它应该与您的脚本执行相同的操作,但不会在处理过程中回显文件。

我建议您在使用sed -i 命令之前对您的网站进行备份,文件将在未经确认的情况下被覆盖。

更新:

正如@Aaron 所注意到的,sed 可以为您备份与 sed 命令匹配的每个文件,使用 -i 参数后的扩展名作为 -i.bak .请记住在成功替换后从您的网站中删除这些 *.bak 文件。

关于linux - 用于更新链接的 Sed 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35748214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com