Board logo

标题: [文件操作] [已解决]批处理如何提取htm文件里的指定内容/字符串来重命名该文件? [打印本页]

作者: lxh623    时间: 2016-5-13 12:41     标题: [已解决]批处理如何提取htm文件里的指定内容/字符串来重命名该文件?

这里有几个文件。我自己有两千个。是下载的htm文件。
想提取部分字段来重命名htm。标题和作者字段,格式是,“标题--作者”,作者之间用逗号分隔。
原件中,标题有时候涉及到换行。作者也有两三行的可能。
谢谢!
http://pan.baidu.com/s/1dE7xjih
作者: WHY    时间: 2016-5-13 15:14

试试
  1. @if (0)==(0) echo off
  2. for /f "delims=" %%i in ('dir /b *.htm^|cscript //nologo //e:jscript "%~f0"') do ren %%i
  3. pause & exit
  4. @end
  5. var getContent = function(strFile){
  6.     var ado = new ActiveXObject('ADODB.Stream');
  7.     ado.Type = 2;
  8.     ado.Charset = 'UTF-8';
  9.     ado.Open();
  10.     ado.LoadFromFile(strFile);
  11.     var s = ado.ReadText(-1);
  12.     var title = s.match(/<title>(.+)<\/title>/i)[1];
  13.     var author = [];
  14.     var reg = /'color:#003300'>(.+?)</ig;
  15.     while(arr = reg.exec(s)){author.push(arr[1])}
  16.     ado = null;
  17.     return (title + '--' + author).replace(/[\/\\|*?<>":]/g, '')
  18. }
  19. while(!WSH.StdIn.AtEndOfStream){
  20.     var f = WSH.StdIn.ReadLine();
  21.     var ext = f.replace(/.+(\.html?)$/i, '$1');
  22.     WSH.Echo('"' + f + '" "' + getContent(f) + ext + '"');
  23. }
复制代码

作者: lxh623    时间: 2016-5-13 18:04

试试
WHY 发表于 2016-5-13 15:14

谢谢了。我这里还是不行,运作一下,就说打不开'ADODB.Stream',停止了。
作者: WHY    时间: 2016-5-13 20:24

本帖最后由 WHY 于 2016-5-14 23:14 编辑

回复 3# lxh623


    我这里测试没有你所说的问题,win7 SP1 64bit 中文旗舰版系统

试试下面的代码,需要用到第三方工具  
http://batch-cn.qiniudn.com/tool/win_iconv.exe
http://batch-cn.qiniudn.com/tool/2.22/grep.exe
  1. @echo off & setlocal enabledelayedexpansion
  2. set "reg=(?<=<title>).+(?=</title>)|(?<='color:#003300'>).+?(?=<)"
  3. for /f "delims=" %%i in ('dir /b *.htm') do (
  4.     set "newName="
  5.     for /f "delims=" %%j in ('win_iconv -c -f utf8 -t gb2312 "%%i" ^| grep -ioP "%reg%"') do (
  6.         if not defined newName (set newName=%%j--)else set "newName=!newName!%%j,"
  7.     )
  8.     for %%j in (/ \ : ^| ^< ^> ^") do set "newName=!newName:%%j=!"
  9.     set "newName=!newName:?=!"
  10.     ren "%%i" "!newName:~0,-1!%%~xi"
  11. )
  12. pause
复制代码

作者: WHY    时间: 2016-5-13 20:35

本帖最后由 WHY 于 2016-5-14 23:11 编辑

win7 及以上系统也可以这样,可读性差了点
  1. @echo off
  2. set "r1=(?i)<title>(.+)</title>"
  3. set "r2=(?i)''color:#003300''>(.+?)<"
  4. PowerShell -c "dir @('*.htm','*.html')|%%{$a=type $_ -encoding utf8;$b=[regex]::match($a,'%r1%').groups[1].value;$c=([regex]::matches($a,'%r2%')|%%{$_.groups[1].value}) -join ',';ren $_ -newName (($b+'--'+$c+$_.Extension) -replace '[/\\|*?<>:\"]')}"
  5. pause
复制代码





欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2