用于更新链接的{sed}脚本

时间:2016-03-02 13:12:42

标签: linux bash sed

我是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

1 个答案:

答案 0 :(得分:0)

脚本中的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可以在-i param -i.bak之后使用扩展名为你备份sed命令匹配的每个文件。请记住在成功替换后从您的网站删除这些* .bak文件。