You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本批量注释/取消HTML img标签异常问题求助

解决Bash脚本处理HTML img标签注释的问题

问题场景

编写了一段Bash脚本用于检查指定文件列表中的文件是否存在:

  • 文件不存在时,给HTML中对应src属性的img标签添加<!-- -->注释
  • 文件存在时,取消该img标签的注释

但脚本出现部分行重复添加注释、部分行无法取消注释的问题。

原脚本代码:

#!/bin/bash

# Define the list of file names to match
FILE_LIST=("2375.jpg" "375_.jpg" "875.jpg")

# Define the path to the HTML file
HTML_FILE="./test.html"

# Loop over the file list
for FILE in "${FILE_LIST[@]}"; do
    # Check if the file exists in the folder
    if [ ! -f "$FILE" ]; then
        # File is missing, search for the line containing the file name in the HTML file and comment it out
        sed -i "/<img.*src=\"\./$FILE\".*>/ s/^/<!-- /; /<img.*src=\"\./$FILE\".*>/ s/$/ -->/" "$HTML_FILE"
    else
        # File exists, search for the line containing the file name in the HTML file and uncomment it if it's currently commented out
        sed -i "/<img.*src=\"\./$FILE\".*>/ s/<!--\(.*\)-->/\1/" "$HTML_FILE"
    fi
done

示例HTML内容:

<img src="./3723.jpg" class="Fire" border="1" id="map15" onclick="showGraph(this);return true;">
<img src="./775.jpg" class="Fire" border="1" id="map16" onclick="showGraph(this);return true;">
<!--<img src="./575.jpg" class="Fire" border="1" id="map17" onclick="showGraph(this);return true;">-->

问题分析

  1. 重复注释问题:原注释逻辑未判断目标行是否已被注释,每次执行都会给匹配到的行添加注释标签,导致重复嵌套注释(如<!-- <!-- <img...> --> -->)
  2. 无法取消注释问题:取消注释时的匹配模式只能识别未被注释的img行,已注释的行开头是<!--,根本不会被匹配到,因此无法执行取消操作

修正后的脚本

#!/bin/bash

FILE_LIST=("2375.jpg" "375_.jpg" "875.jpg")
HTML_FILE="./test.html"

for FILE in "${FILE_LIST[@]}"; do
    # 转义文件名中的特殊字符,避免sed正则解析报错
    ESCAPED_FILE=$(printf '%s' "$FILE" | sed 's/[\/&]/\\&/g')
    
    if [ ! -f "$FILE" ]; then
        # 仅对未被注释的目标img行添加注释:匹配行首无<!--的img行
        sed -i "/^[^<]*<img.*src=\".\/$ESCAPED_FILE\".*>/ s/^/<!-- /; s/$/ -->/" "$HTML_FILE"
    else
        # 仅对已被注释的目标img行取消注释:匹配包含注释标签和目标img的行
        sed -i "/<!--.*<img.*src=\".\/$ESCAPED_FILE\".*-->/{s/^<!-- //; s/ -->$//}" "$HTML_FILE"
    fi
done

关键修正点

  • 精准匹配逻辑:
    • 注释操作时,用^[^<]*确保只处理未被注释的img行,避免重复注释
    • 取消注释时,直接定位包含注释标签和目标img的行,确保能找到已注释的内容
  • 特殊字符转义:新增ESCAPED_FILE处理文件名中的/、&等特殊字符,防止sed正则解析出错
  • 简化sed命令:将同一匹配条件下的多个替换操作合并到一个sed块中,提升执行效率和代码可读性

内容的提问来源于stack exchange,提问作者Pad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:20:42