如何扫描所有现有的HTML并添加代码片段?

时间:2018-04-20 07:31:26

标签: php html

我有一个带有Excel自动生成的html文件的ftp文件夹,我需要能够通过在头部插入一个css链接来设置它们的样式

我能用这些代码吗?基本上它会扫描所有现有的HTML或新的,并添加css片段,如果它还没有。

使用php scandir和glob进行谷歌搜索但没有运气

感谢

1 个答案:

答案 0 :(得分:-1)

这个bash脚本可以解决这个问题。如果您使用的是Windows,则可能必须安装linux子系统才能运行该脚本。

使用只需更改变量HEADERLINE。

工作原理:

脚本遍历所有* .html文件,使用head -n 1获取第一行并使用grep将其与HEADERLINE进行比较。如果未找到,则会创建一个新的临时文件并将其复制回原始文件。

#!/bin/bash
#===============================================================================
#
#          File: addhead.sh
# 
#         Usage: ./addhead.sh 
# 
#   Description: Adds HEADERLINE to all html files if it's not already present
# 
#       Options: ---
#  Requirements: ---
#          Bugs: ---
#         Notes: ---
#        Author: Bernhard Brunner (bernhard.brunner@it-transforms.ch)
#  Organization: 
#       Created: 2018/04/20 09:32
# Last modified: 2018-04-20 09:44
#      Revision:  ---
#===============================================================================

tmpfile=`mktemp`
HEADERLINE='<link rel="stylesheet" href="https://test.com/my.css>'

function error()
{
    echo "*** ERROR:" $*
    exit 1
}

for f in *.html ; do 
    if ! head -n 1 $f | grep -q "$HEADERLINE" ; then
        echo adding header to $f
        echo "$HEADERLINE" > $tmpfile
        cat $f >> $tmpfile || error reading $f
        cp $tmpfile $f || error writing $f
    fi
done
rm $tmpfile