【问题标题】:Delete spaces around specific tags in an html file in shell删除 shell 中 html 文件中特定标签周围的空格
【发布时间】:2020-03-03 22:16:21
【问题描述】:

我正在寻找一个 shell 脚本来缩小更少的 html 文件,但是我遇到了一个问题。

我想删除特定 html 标记每一侧的空间,这些标记是从文件中读取的。使用“perl”,我做不到,什么也没有发生,使用 sed 在 2 个命令中,我几乎得到了我想要的。在下面的示例中,删除了一些标签之间的空格,但不是全部,在“section”标签级别存在问题,“h2”也是,但是模式匹配...

for tag in $tag_file ; do 
    #   perl -e '$comHtml=<>; $comHtml=~s/ *(<${tag} *.* *>) */\1/g; print $comHtml' < tmp_html
    sed -i -r -e "s: *(<${tag} *.* *>) *:\1:gI" ./tmp_html
    sed -i -r -e "s: *(</${tag} *.* *>) *:\1:gI" ./tmp_html
    done

这里,$tag_file 包含从文件中获取的特定标签,例如 $tag_file = html \n head \n section \n ...

输入html:

<!doctype html> <html lang="fr"> <head> <meta charset="UTF-8"> <title>La gazette de L-INFO</title> <link rel="stylesheet" type="text/css" href="./styles/gazette.css"> </head> <body> <nav> <ul> <li><a href="#">Accueil</a></li> <li><a href="./html/actus.html">Toute l'actu</a></li> <li><a href="./php/recherche.php">Recherche</a></li> <li><a href="./html/redaction.html">La rédac'</a></li> <li><a href="#">jbigoude</a> <ul> <li><a href="./php/compte.php">Mon profil</a></li> <li><a href="./php/nouveau.php">Nouvel article</a></li> <li><a href="./php/deconnexion.php">Se déconnecter</a></li> </ul> </li> </ul> </nav> <header> <img src="./images/titre.png" alt="La gazette de L-INFO" width="780" height="83"> <h1>Le site de désinformation n°1 des étudiants en Licence Info</h1> </header> <main> <section class="centre"> <h2>&Agrave; la Une</h2> <a href="./php/article.php?id=XXX"> <img src="images/hacker.jpg" alt="Un mouchard dans un corrigé de Langages du Web"><br> Un mouchard dans un corrigé de Langages du Web </a> <a href="./html/article.html"> <img src="images/hymne.jpg" alt="Votez pour l'hymne de la Licence"><br> Votez pour l'hymne de la Licence </a> <a href="./php/article.php?id=XXX"> <img src="images/melenchon.jpg" alt="L'amphi Sciences Naturelles bientôt renommé amphi Mélenchon"><br> L'amphi Sciences Naturelles bientôt renommé amphi Mélenchon </a> </section> <section class="centre"> <h2>L'info brûlante</h2> <a href="./php/article.php?id=XXX"> <img src="images/walkingdead.jpg" alt="Il avait annoncé 'Je vais vous défoncer' l'enseignant relaxé"><br> Il leur avait annoncé "Je vais vous défoncer" l'enseignant relaxé </a> <a href="./php/article.php?id=XXX"> <img src="images/pingouins.jpg" alt="Des pinguoins dans l'amphi B"><br> Toute une famille de pingouins découverte dans l'amphi B </a> <a href="./php/article.php?id=XXX"> <img src="images/macron.jpg" alt="Emmanuel Macron obtient sa Licence d'Info en EAD"><br> Emmanuel Macron obtient sa Licence Info en EAD </a> </section> <section class="centre"> <h2>Les incontournables</h2> <a href="./php/article.php?id=XXX"> <img src="images/arnaque.jpg" alt="Arnaque au devoir corrigé de TLSP"><br> Une arnarque au corrigé de TL mise à jour </a> <a href="./php/article.php?id=XXX"> <img src="images/calendrier.jpg" alt="Le calendier des Dieux de la Licence bientôt disponible"><br> Le calendier des Dieux de la Licence bientôt disponible </a> <a href="./php/article.php?id=XXX"> <img src="images/sondage.jpg" alt="Allez-vous réussir votre année ?"><br> Résultat de notre sondage : allez-vous réussir votre année ? </a> </section> <section> <h2>Horoscope de la semaine</h2> <p>Vous l'attendiez tous, voici l'horoscope du semestre pair de l'année 2019-2020. Sans surprise, il n'est pas terrible...</p> <table id="horoscope"> <tr> <td>Signe</td> <td>Date</td> <td>Votre horoscope</td> </tr> <tr> <td>&#9800; Bélier</td> <td>du 21 mars<br>au 19 avril</td> <td rowspan="4"> <p>Après des vacances bien méritées, l'année reprend sur les chapeaux de roues. Tous les signes sont concernés. </p> <p>Jupiter s'aligne avec Saturne, péremptoirement à Venus, et nous promet un semestre qui ne sera pas de tout repos. Février sera le mois le plus tranquille puisqu'il ne comporte que 29 jours.</p> <p>Les fins de mois seront douloureuses pour les natifs du 2e décan au moment où tomberont les tant-attendus résultats du module d'<em>Algorithmique et Structures de Données</em> du semestre 3.</p> </td> </tr> <tr> <td>&#9801; Taureau</td> <td>du 20 avril<br>au 20 mai</td> </tr> <tr> <td>...</td> <td>...</td> </tr> <tr> <td>&#9811; Poisson</td> <td>du 20 février<br>au 20 mars</td> </tr> </table> <p>Malgré cela, notre équipe d'astrologues de choc vous souhaite à tous un bon semestre, et bon courage pour le module de <em>Système et Programmation Système</em>.</p> </section> </main> <footer>&copy; Licence Informatique - Janvier 2020 - Tous droits réservés</footer> </body> </html> 

输出html:

<!doctype html><html lang="fr"><head><meta charset="UTF-8"><title>La gazette de L-INFO</title><link rel="stylesheet" type="text/css" href="./styles/gazette.css"></head><body><nav><ul> <li><a href="#">Accueil</a></li> <li><a href="./html/actus.html">Toute l'actu</a></li> <li><a href="./php/recherche.php">Recherche</a></li> <li><a href="./html/redaction.html">La rédac'</a></li> <li><a href="#">jbigoude</a> <ul> <li><a href="./php/compte.php">Mon profil</a></li> <li><a href="./php/nouveau.php">Nouvel article</a></li> <li><a href="./php/deconnexion.php">Se déconnecter</a></li></ul> </li> </ul></nav><header> <img src="./images/titre.png" alt="La gazette de L-INFO" width="780" height="83"><h1>Le site de désinformation n°1 des étudiants en Licence Info</h1></header><main><section class="centre"><h2>&Agrave; la Une</h2> <a href="./php/article.php?id=XXX"> <img src="images/hacker.jpg" alt="Un mouchard dans un corrigé de Langages du Web"><br> Un mouchard dans un corrigé de Langages du Web </a> <a href="./html/article.html"> <img src="images/hymne.jpg" alt="Votez pour l'hymne de la Licence"><br> Votez pour l'hymne de la Licence </a> <a href="./php/article.php?id=XXX"> <img src="images/melenchon.jpg" alt="L'amphi Sciences Naturelles bientôt renommé amphi Mélenchon"><br> L'amphi Sciences Naturelles bientôt renommé amphi Mélenchon </a></section> <section class="centre"> <h2>L'info brûlante</h2> <a href="./php/article.php?id=XXX"> <img src="images/walkingdead.jpg" alt="Il avait annoncé 'Je vais vous défoncer' l'enseignant relaxé"><br> Il leur avait annoncé "Je vais vous défoncer" l'enseignant relaxé </a> <a href="./php/article.php?id=XXX"> <img src="images/pingouins.jpg" alt="Des pinguoins dans l'amphi B"><br> Toute une famille de pingouins découverte dans l'amphi B </a> <a href="./php/article.php?id=XXX"> <img src="images/macron.jpg" alt="Emmanuel Macron obtient sa Licence d'Info en EAD"><br> Emmanuel Macron obtient sa Licence Info en EAD </a> </section> <section class="centre"> <h2>Les incontournables</h2> <a href="./php/article.php?id=XXX"> <img src="images/arnaque.jpg" alt="Arnaque au devoir corrigé de TLSP"><br> Une arnarque au corrigé de TL mise à jour </a> <a href="./php/article.php?id=XXX"> <img src="images/calendrier.jpg" alt="Le calendier des Dieux de la Licence bientôt disponible"><br> Le calendier des Dieux de la Licence bientôt disponible </a> <a href="./php/article.php?id=XXX"> <img src="images/sondage.jpg" alt="Allez-vous réussir votre année ?"><br> Résultat de notre sondage : allez-vous réussir votre année ? </a> </section> <section> <h2>Horoscope de la semaine</h2><p>Vous l'attendiez tous, voici l'horoscope du semestre pair de l'année 2019-2020. Sans surprise, il n'est pas terrible...</p> <table id="horoscope"> <tr> <td>Signe</td> <td>Date</td> <td>Votre horoscope</td> </tr> <tr> <td>&#9800; Bélier</td> <td>du 21 mars<br>au 19 avril</td> <td rowspan="4"> <p>Après des vacances bien méritées, l'année reprend sur les chapeaux de roues. Tous les signes sont concernés. </p> <p>Jupiter s'aligne avec Saturne, péremptoirement à Venus, et nous promet un semestre qui ne sera pas de tout repos. Février sera le mois le plus tranquille puisqu'il ne comporte que 29 jours.</p> <p>Les fins de mois seront douloureuses pour les natifs du 2e décan au moment où tomberont les tant-attendus résultats du module d'<em>Algorithmique et Structures de Données</em> du semestre 3.</p> </td> </tr> <tr> <td>&#9801; Taureau</td> <td>du 20 avril<br>au 20 mai</td> </tr> <tr> <td>...</td> <td>...</td> </tr> <tr> <td>&#9811; Poisson</td> <td>du 20 février<br>au 20 mars</td> </tr> </table> <p>Malgré cela, notre équipe d'astrologues de choc vous souhaite à tous un bon semestre, et bon courage pour le module de <em>Système et Programmation Système</em>.</p> </section></main><footer>&copy; Licence Informatique - Janvier 2020 - Tous droits réservés</footer></body></html>

【问题讨论】:

  • 你的问题表达的不是很清楚,便于理解。我试图了解$tag_file 的值是什么,在它用作数组的shell 中。您可以使用perl -0777 -pe 's/(&gt;)\s*(&lt;)/$1$2/g' tmp_html 删除html 标记之间的所有空格。但同样,您在消息中仅提及特定标签。不清楚,因为 $tag_file 是未知的。
  • 如果您使用资源稀缺的嵌入式系统,您的问题将是有意义的。否则,现在可以将 Web 服务器配置为 压缩 传输的数据以 缩小 流量。
  • 我指定 $ tag_files 变量包含获取到的特定标签的名称 tag_file = $ (cat $ VAR) $ VAR 是一个文件的路径,其中标签是这样编写的:html section ... ,因此标签将取值为 1 "html" etc .. 所以我想删除 标签周围的空格
  • 我只是想在业余时间做一些简单的事情
  • @Antolife -- 请编辑您的代码并添加一段演示您如何获取内容tag_file = $(cat $VAR)。演示对某个文件名的 $VAR 变量的赋值是一个好主意(也许注释不是坏主意)。这将使示例代码更加完整,并且您将避免我问过的问题从您那里提取这些信息。

标签: html perl sed minify hyphen


【解决方案1】:

你的 perl 行的主要问题是你的引用;你使用了单引号,这意味着你不必转义 Perl 变量,但这也意味着 shell 变量 ${tag} 将由 Perl(它是空的)而不是 shell 解释。您可以通过将它们作为参数或环境变量传递来更轻松地从 Perl 访问 shell 变量。您也没有使用 -i 开关进行就地编辑,因此您只是将更改打印到 STDOUT。

安装 ojo 后,您可以使用适当的 HTML 解析器执行此操作,因此不会受到边缘情况的影响:

env tag=$tag perl -0777 -pi -CS -Mojo -e '$_ = x($_);
  $_->find($ENV{tag})->each(sub {
    $_->content($_->content =~ s/\A *//r =~ s/ *\z//r);
    my ($p, $n) = ($_->previous_node, $_->next_node);
    $p->content($p->content =~ s/ *\z//r) if defined $p and ($p->type eq "text" or $p->type eq "raw");
    $n->content($n->content =~ s/\A *//r) if defined $n and ($n->type eq "text" or $n->type eq "raw");
  })' tmp_html

-0777 开关确保文件将在一个步骤中而不是逐行操作,-pi 将代码包装在一个循环中,该循环将输入分配给$_,然后就地更新该文件$_-CS 的结果值确保它会从 UTF-8 解码,然后解析和编码。

来自 ojo 的 x 函数创建一个 Mojo::DOM 对象,然后该对象可以找到所请求标签的每个实例并对其进行操作(包括其内容和结束标签)。

替换操作:s/\A *//rs/ *\z//r 分别删除字符串开头或结尾的所有空格字符,并返回修改后的字符串(/r 阻止它就地操作,因此您可以将其与Mojo::DOM 的内容方法)。要改为删除任何空白字符(包括换行符),请使用 s/\A\s*//rs/\s*\z//r

【讨论】:

  • 我是 perl 新手;因此,我发现很难理解所有内容.. 对于输出标准输出,我知道我想在终端中进行测试,您能否告诉我是否可以使用 sed 或更简单的 perl 命令(如果有)。在 perl 之外,你对 env 的解释很清楚我想我明白这一点;谢谢
  • 如果你删除-i(所以只使用-p),那么它将输出到STDOUT而不是就地编辑。如果您从 STDIN 输入而不是将文件名作为参数传递,则相同。
  • 没问题;和 sed ?
  • 我不知道 sed,但我已经添加了一些更多的解释。
  • 我不会尝试,因为使用直接正则表达式在 HTML 上操作是 extremely complicated to do correctly,并且没有比 ojo/Mojo::DOM 更简单的命令行 HTML 解析器。您的要求实际上并没有那么简单。
【解决方案2】:

在与 OP 进行了一些沟通后,我希望我能正确理解问题。

HTML 标签存储在单独的文件中,每行一个 (tag_file.txt),在单独的文件中我们有 HTML 网页代码 (file.html)。

代码应去除 HTML 网页代码 (file.html) 中标记文件 (tag_file.txt) 中指定的标记 [打开、关闭] 周围的空格。

注意:在没有 shell 帮助的情况下使用 perl 脚本完成处理(缩短处理时间)

use strict;
use warnings;
use feature 'say';

my $tag_file    = 'tag_file.txt';
my $html_file   = 'file.html';

open my $fh_tag, '<', $tag_file         # open tag file
    or die "Couldn't open $tag_file: $!";

my @tags = <$fh_tag>;                   # read tags into array
chomp @tags;                            # remove eol from tag lines

close $fh_tag;                          # close tag file

open my $fh_html, '<', $html_file       # open html file
    or die "Couldn't open $html_file: $!";

my $html = do { local $/; <$fh_html> }; # read whole file into variable

close $fh_html;                         # close html file

# now make substitution for each read tag
for my $tag (@tags) { $html =~ s!\s*(</?$tag\s*.*?>)\s*!$1!g; }

say $html;

tag_file.txt的内容

html
head
body
section

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多