首页 > 解决方案 > 如果单词在同一段落中匹配,则 shell 或 PHP 删除 HTML 注释

问题描述

我需要验证 HTML 注释中的单词是否包含在同一行中,在这种情况下,删除注释。否则,保留评论。

同时,脚本需要忽略代词、副词、冠词。我已经有一个清单,超过 100 百字。像这样:

“那个”、“这个”、“我”、“我”、“你”、“她”、“她”、“他”、“他”、“它”、“他们”、“他们”、“那个” ”、“威奇”等...

这是一行的示例:

text <!-- They are human # life --> text text <!-- the rights --> text the human text

运行脚本后:

text text text <!-- the rights --> text the human text

恢复:

  1. 在同一行中可以有很多评论,而不仅仅是一个。
  2. 脚本需要忽略我的代词、副词等列表...
  3. 脚本需要忽略其他评论的话。
  4. 不敏感的情况。
  5. 这些文件有超过一千行。
  6. 通常在评论中我有这个字符#(我希望不是问题)。

标签: phpshellgrep

解决方案


正如其他人所提到的,您应该进行一些研究,说明您尝试过什么以及为什么它不起作用。

话虽如此,我发现这是一个有趣的小挑战,所以我决定试一试。

我假设有两个文件,“file.html”我们要修改,“words.txt”列出要忽略的单词,用换行符 (\n) 分隔。这个脚本应该可以解决问题:

#!/bin/bash

FILE="file.html"
WORDS="words.txt"

#Set array delimiter to '\n':
IFS=$'\n'

#Find all comments within the file:
comments="$(cat $FILE | grep -oP '<!--[^<]+-->' | sort | uniq)"

for comment in $comments; do

  #Words In Comment. Gets all words in the comment.
  wic="$(echo $comment | head -1 | grep -oP '[^\s]+' | grep -v '<' | grep -v '>')"

  words="$(cat $WORDS)"

  #Filtered Words. It's $wic without any of the words in words.txt
  fw="$(echo $wic $words $words | tr ' ' '\n' | sort | uniq -u)"

  #if any remain
  if [ ! -z "$fw" ]
  then

    for word in $fw; do
      #Gets all lines with both the comment and the word outside the comment 
      lines="$(cat $FILE | grep -P "$comment.+$word|$word.+$comment")"

      #If it finds any
      if [ ! -z "$lines" ]
      then
        for line in $lines; do

          #Generate the replacement line
          replace="$(echo $line | sed "s/$comment//g")"

          #Replace the line with the replacement in the file
          sed -i "s/$line/$replace/g" $FILE

        done
      fi
    done
  fi
done

它并不完美,但可以完成工作。在具有以下内容的文件上对其进行了测试:

text <!-- foo # --> foo
text <!-- bar # --> foo
text <!-- bar # --> bar
text <!-- bar # --> text <!-- something # --> something bar
text <!-- foo # --> text <!-- bar # --> text foo bar

使用以下 words.txt:

foo

并得到了预期的结果:

text <!-- foo # --> foo
text <!-- bar # --> foo
text  bar
text  text  something bar
text <!-- foo # --> text  text foo bar

推荐阅读