perl 替换制定的文本块

替换的样本块如下:  <div class="comment" style="width: 635px;">             <!--兼容版,可保证页面完全兼容-->             <div id="SOHUCS"></div>    ...

替换的样本块如下:


 <div class="comment" style="width: 635px;">

            <!--兼容版,可保证页面完全兼容-->

            <div id="SOHUCS"></div>

            <script>

                (function(){

                    var appid = 'cyrucdH',

                            conf = 'prod_9a080b2b83485f3280c5d48ecfa62f';

                    var doc = document,

                            s = doc.createElement('script'),

                            h = doc.getElementsByTagName('head')[0] || doc.head || doc.documentElement;

                    s.type = 'text/javascript';

                    s.charset = 'utf-8';

                    s.src =  'http://assets.changyan.sohu.com/upload/changyan.js?conf='+ conf +'&appid=' + appid;

                    h.insertBefore(s,h.firstChild);

                })()

            </script>

        </div>



perl -i -0p  -e's# <div class=\"comment\".*?</div>.*?</div>##sm' *.html


其中修饰符 /s 指 匹配换行符 /m 以^ 和$ 定位符的 多行匹配,  -0  的解析见如下:


A couple of notes in the above expression:

  • The "-i" option tells Perl to perform in-place editing, meaning that Perl reads the input file, makes substitutions, and writes the results back to the same input file. If you want to dry-run the changes, you can omit this option, in which case the results will be shown to stdout without modifying the input file.
  • The "-0" option turns Perl into "file slurp" mode, where Perl reads the entire input file in one shot (intead of line by line). This enables multi-line search and replace.
  • The "-pe" option allows you to run Perl code (pattern matching and replacement in this case) and display output from the command line.



-n -p 都会使用 <> 将所有 @ARGV 参数当作文件来逐行运行(有循环的意思哦,经常和其它参数一起处理文件),会将读入的内容隐式的逐一按行来遍历文件.每一行将缺省保存在 $_;但-p 会将内容“重复”打印出来,而-n更倾向与打印满足某种条件的行(这这里还有一些有用的变量比如$. 表示当前行的行数)


#perl -lane ‘print $F[0] + $F[-2]‘ 这个神奇的地方在于-a,使用-a后.因为-n分行读进来,然后-a给数据分割成@F的数组.


#perl -ne ‘print if /^START$/ .. /^END$/' 打印正则中从$start到$end的地方


#perl -ne ‘print if $. >= 15; exit if $. >= 17;' 有效地打印数字范围中的行


#perl -p -i.bak -e ‘s/\bfoo\b/bar/g' *.c 原地修改 -i 开关的神奇之处在于它对 @ARGV 中的每个文件都用该脚本对该文件输出所产生的文件版本进行替代


#perl -ne ‘print scalar reverse $_' test 给文件中的内容反向排序,比如文件中有abc,就会变成cba



  • 发表于 2019-09-24 13:37
  • 阅读 ( 48 )

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
石天
石天

437 篇文章

作家榜 »

  1. shitian 662 文章
  2. 石天 437 文章
  3. 每天惠23 33 文章
  4. 小A 29 文章