批量替换css里图片的相对路径为绝对路径

最近好像总是发些shell的东西,木办法,最近没怎么写js的样子…
————————————————————–
恩,之所以要替换成绝对路径,是因为css和图片host在不同域的server上,写完刚在站里的静态跑过,好像木啥大问题~
效果:

/img/a.gif 会被替换成 http://domain/img/a.gif
../img/a.gif 会被替换成类似 http://domain/parent/img/a.gif

使用方法如下(linux only)

#直接跟目录就好了
sh r2a.sh /opt/static

脚本下载点这里:r2a.zip
贴出shell的源码,便于不想下载又想看看shell的同学,还有个python脚本,就不贴了,没啥含量

#!/bin/sh
#@author emptyhua@gmail.com

#本地根目录
LROOT="/home/hualu/work/static"
#远程根目录
RROOT="http://myimgdomain.cn"
#要处理目录的绝对路径
CP="`cd $1;pwd`"
#用于转换相对路径为绝对路径的python脚本的路径
PY="/home/hualu/bin/get_sed_rule.py"
LROOTR="`echo ${LROOT} | sed 's/\\//\\\\\//g;s/\\./\\\\\\./g'`"
RROOTR="`echo ${RROOT} | sed 's/\\//\\\\\//g;s/\\./\\\\\\./g'`"

echo "执行路径${CP}"
find ${CP} -name "*.css" > /tmp/_r2a_css_files 

cat /tmp/_r2a_css_files | while read f;do
    echo "处理:${f}"
    dir="`dirname \"${f}\"`"
#获取css文件所在的发布目录
    echo "${dir}" | sed "s/${LROOTR}/${RROOTR}/" > /tmp/_r2a_remote_path
    remote_path="`cat /tmp/_r2a_remote_path`"
#收集要处理的图片路径
    cat $f | awk '{print NR,"####",$0}' | grep "url([\"\']*\.\{1,2\}" > /tmp/_r2a_file
    cat /tmp/_r2a_file | sed -e "s/url([\"\']*\(\.\.[^\)]*\)[\"\']*)/开始\1始开/g" -e "s/####[^始]*开始/:/;s/始开[^始]*$/:/;s/始开[^始]*开始/:/g" > /tmp/_r2a_cssimage
    echo '' > /tmp/_r2a_sed_rule
#将相对路径转换为绝对路径,并生成sed语句
    cat /tmp/_r2a_cssimage | while read r;do
        rule="`python \"${PY}\" \"${r}\" \"${remote_path}\"`"
        echo "${rule};" >> /tmp/_r2a_sed_rule 
    done
    sed_rule="`cat /tmp/_r2a_sed_rule | tr -d '\\n'`"
#利用sed处理文件
    sed -i -e "$sed_rule" "${f}"
    sed -i -e "s/url(\([\"\']*\)\//url(\1${RROOTR}\//g" "${f}" 
done

rm /tmp/_r2a_css_files
rm /tmp/_r2a_remote_path
rm /tmp/_r2a_file
rm /tmp/_r2a_cssimage
rm /tmp/_r2a_sed_rule

已发布

分类

来自

标签:

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据