1 (изменено: DD, 2012-02-02 20:25:11)

Тема: AHK: Поиск по файлам строк, содержащих слово

Win+F — показать окно скрипта.

Вопрос: как научить его вести поиск также по документам, кодированным UTF-8 ?

#SingleInstance force

#SC021::		;Win+F
Word_Searcher:
  hWnd := WinExist("A")
  WinGetClass wClass, ahk_id %hWnd%
    Res := GetWindowsExplorerPath(hWnd)
      IfWinActive, ahk_class Progman
      Res := A_DESKTOP

foldersel=%Res%
targetFile = %A_ScriptDir%\FLines.html

Gui, 34:+LastFound +Caption -minimizebox
Gui, 34:Add, Edit, r1 w300  yp+15          vsearchedWord, %searchedWord%
Gui, 34:Add, Button,  xp+300 default w80 , Искать
Gui, 34:Add, Edit, r1 w300  xp-300 yp+22   vfoldersel, %foldersel%
Gui, 34:Add, Button,  xp+300         w80 , Обзор...
Gui, 34:Add, Checkbox, Checked0  xp-300 yp+40  vrec, смотреть в подпапках
Gui, 34:Add, Checkbox, gextents  Checked0  xp+190 yp-0  vext, с расширением
Gui, 34:Add, ComboBox , disabled Uppercase xp+125 w60 vextchoice, AHK|BAT|CMD|CSS|HTM|HTML|PHP|TXT|LOG|INF|INI|HTA|JS|VBS|WSF|REG
extents:
ControlGet, variab, Checked,, Button8, 
Control, Enable,, ComboBox1,
Gui, 34:Show, w400 h120, LinesCatcher
return
34ButtonОбзор...:
FileSelectFolder, obzor, ,
IF (obzor<>"")
GuiControl,34:, foldersel, %obzor%
return
34ButtonИскать:
CoordMode, ToolTip, Screen
ToolTip, ...,0,0
Gui, Submit, hide
SetWorkingDir %foldersel%
IF ext=1
extention = %extchoice%
ELSE
extention=*

FileDelete, %A_ScriptDir%\FLines.html
{
  FileAppend,
  (LTrim
  <html>`n<head>`n<title>[FLines]</title><base target="parent" />
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1251"/>
  <STYLE type="text/css">`n<!--
  body {BACKGROUND:url('/n.gif') no-repeat; BACKGROUND-ATTACHMENT:fixed; BORDER:none;
    BACKGROUND-COLOR:#A8C1AE; FONT-FAMILY:serif; MARGIN:5`% 22`% 20`% 22`%; PADDING:0;}
  #header {POSITION:fixed; Z-INDEX:1; TOP:0; RIGHT:0; //POSITION:absolute; TOP:expression(
    document.getElementsByTagName( 'body' )[0].scrollTop + "px");}`n#content {}
  a {COLOR:#990000; FONT-FAMILY:Tahoma, Helvetica, Geneva;
    FONT-SIZE:7.5pt; FONT-WEIGHT:bold; TEXT-DECORATION:none;}
  a:hover {COLOR:blue;}`na:visited {COLOR:#990099;}
  b {BACKGROUND-COLOR:#FF9999; COLOR:#000000; FONT-SIZE:17px;
    BORDER-TOP:2px solid #bb4000; BORDER-BOTTOM:2px solid #bb4000;}
  td {BACKGROUND-COLOR:#effeee; BORDER:1px solid black;
    PADDING:7px 13px 7px 13px; BORDER-BOTTOM:0px; FONT-SIZE:16px;}
  #searchbox {WIDTH:220px; HEIGHT:22px; LINE-HEIGHT:18px; border:1px #728776 solid;
    background-color:#EFFEEE;}`n.hidden {DISPLAY:none;}
  -->`n</STYLE>

  <script type="text/javascript">
  var keyTimerId=0;
  function prevEle(e){do{e=e.previousSibling} while(e && e.nodeType != 1); return e};
  function nextEle(e){do{e=e.nextSibling} while(e && e.nodeType != 1); return e};
  function isVisible(e){var rows=e.rows; for(var i=0, r; r=rows[i]; i++){if(!r.className || r.className == 'visible')return true}};
  function find(){var div, tb, h; var val=document.getElementById('searchbox').value.toLowerCase();
  var lnks=document.getElementsByTagName('span');for(var i=0, li; li=lnks[i]; i++){
  div=li.parentNode.parentNode; div.className=((li.textContent || li.innerText).toLowerCase().indexOf(val) != -1) ? 'visible' : 'hidden';
  if(!nextEle(div)){tb=div.parentNode.parentNode; h=prevEle(tb);
  if(isVisible(tb)){tb.className='visible'; h.className='visible'}else{tb.className='hidden'; h.className='hidden'};}}};
  function addInfo(text) {var fieldRef;if(fieldRef=document.getElementById('searchbox'))
  {fieldRef.value = text;find()}return false;}
  </script>`n</head>`n<body onDblClick="document.getElementById('searchbox').focus()">`n`n<div id="header">
  <INPUT type="text" value="Быстрый поиск" id="searchbox"
  onfocus="if(this.value==this.defaultValue)this.value='';"
  onblur="if(!this.value)this.value=this.defaultValue;"
  onkeyup="clearTimeout(keyTimerId);keyTimerId=setTimeout('find()',500);"
  onDblClick="return addInfo('');">`n</div>`n<div id="content">
  <table width=100`% cellspacing=0 cellpadding=0 border=0 style="BORDER-BOTTOM:1px solid #000000;">`n`n`n
), %A_ScriptDir%\FLines.html
}

Loop *.%extention%, 0, %rec%     ;, 0,1  -  искать в подп
{
  If (A_LoopFileFullPath != targetFile)
  {
    Loop Read, %A_LoopFileFullPath%, %targetFile%
    {
      IfInString A_LoopReadLine, %searchedWord%    ;с ней быстрее
      {
        Loop Parse,A_LoopReadLine, `.
        {
          IfInString A_LoopField, %searchedWord%
          {
            Str = %A_LoopField%
            StringReplace, Str, Str, %A_Space%%A_Space%%A_Space%, &nbsp`;&nbsp`;&nbsp`;, All
            StringReplace, Str, Str, %A_Space%%A_Space%, &nbsp`;&nbsp`;, All
           ;StringReplace, Str, Str, %A_Tab%, &nbsp`;&nbsp`;&nbsp`;, All
            StringReplace, Str, Str, <, &lt`;, All
            StringReplace, Str, Str, >, &gt`;, All
            StringReplace, Str, Str, %searchedWord%, <b>%searchedWord%</b>, All
            FileAppend, <tr><td><span>`r`n%Str%.`r`n</span><a href="file:\\%foldersel%\%A_LoopFileFullPath%">%A_LoopFileName%</a>`r`n</td></tr>`r`n`r`n
          }
        }
      }
    }
  }
}

  Run, %A_ScriptDir%\FLines.html
  Sleep, 600
  tooltip
  Gui, 34:destroy
  return

34GuiClose:
34GuiEscape:
  Gui, 34:destroy
  return


; Определение текущего пути в окне Проводника
GetWindowsExplorerPath(_hWnd) 
{ 
   local pid, hMem, pv, pidl, pidl_, explorerPath 
   If (A_OSType = "WIN32_NT") 
   { 
      pid := DllCall("GetCurrentProcessId") 
      SendMessage 0x400 + 12, pid, 0,, ahk_id %_hWnd% 
      hMem := ErrorLevel 
      if (hMem != 0) 
      { 
         pv := DllCall("Shell32\SHLockShared", "UInt", hMem, "UInt", pid) 
         if (pv != 0) 
         { 
            pidl := DllCall("Shell32\ILClone", "UInt", pv) 
            DllCall("Shell32\SHUnlockShared", "UInt", pv) 
         } 
         DllCall("Shell32\SHFreeShared", "UInt", hMem, "UInt", pid) 
      } 
   } 
   Else ; Win9x 
   { 
      SendMessage 0x400 + 12, 0, 0, , ahk_id %_hWnd% 
      pidl_ := ErrorLevel 
      if (pidl_ != 0) 
      { 
         pidl := DllCall("Shell32\ILClone", "UInt", pidl_) 
         DllCall("Shell32\ILGlobalFree", "UInt", pidl_) 
      } 
   } 
   VarSetCapacity(explorerPath, 512, 0) 
   DllCall("Shell32\SHGetPathFromIDList" (A_IsUnicode ?"W":"A"), "UInt", pidl, "Str", explorerPath) 
   Return explorerPath 
}
Return

2 (изменено: DD, 2018-08-22 17:16:32)

Re: AHK: Поиск по файлам строк, содержащих слово

3

Re: AHK: Поиск по файлам строк, содержащих слово

Можно ли разогнать этот скрипт для поиска внутри 7-гиг. файла?


#SingleInstance force
#NoEnv
#MaxMem 400
SetBatchLines -1

Res := "E:\Путь_К_Файлу.txt"
targetFile = %A_ScriptDir%\FLines.txt
searchedWord = ИскомоеСлово

FileDelete, %targetFile%
Loop %Res%
{
   Loop Read, %A_LoopFileFullPath%, %targetFile%
   {
      IfInString A_LoopReadLine, %searchedWord%    ;с ней быстрее
      {
         Loop Parse, A_LoopReadLine, `.
         {
            IfInString A_LoopField, %searchedWord%
            {
               FileAppend, %A_LoopReadLine%`r`n, %targetFile%, UTF-8
            }
         }
      }
   }
}

4 (изменено: teadrinker, 2018-08-22 18:06:59)

Re: AHK: Поиск по файлам строк, содержащих слово

Скрипт разогнать никак нельзя, можно разогнать только скриптописателей. Для быстрого поиска в больших файлах лучше пользоваться утилитой командной строки findstr.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder
+ DD

5

Re: AHK: Поиск по файлам строк, содержащих слово

Нет ли решения по проблеме с кодировкой для findstr, т.к. 7-гиг. файл перекодировать вообще не забавно?

6

Re: AHK: Поиск по файлам строк, содержащих слово

Если строка с кириллицей, создаём временный текстовый файл с поисковым словом, затем применяем ключ /G.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

7

Re: AHK: Поиск по файлам строк, содержащих слово

А если входной файл в UTF-8? Вот так не ищется:

findstr /i /g:finddata.txt E:\BASE\M.txt > results.out

В файле "finddata.txt" кириллич. слово.

8

Re: AHK: Поиск по файлам строк, содержащих слово

Создавайте finddata.txt в UTF-8.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder