Jump to content

from select 1 file, to select all files


Recommended Posts

i have a script that selects  a text file and deletes a line (text input required) in the text file selected

i have to make it remove all lines found on a file i name, toRemoveLines.txt

it has to remove lines from all text files found in a folder

this is the script that has to be modified

where it says "select file" it has to be "select folder"

where it says "line text input" it has to be all lines from a text file

#Include <File.au3>
Global $success = False
$file_name = FileOpenDialog("Select file", @ScriptDir, "All files (*.*)", 1+4)
$line_text_input = InputBox("Line's text", "Line must contain following text:", "line contains this text")
$file_count_lines = _FileCountLines($file_name)
for $i = 0 to $file_count_lines
    $Lines_text_output = FileReadLine($file_name, $i)
    if StringInStr($Lines_text_output, $line_text_input) then
        _FileWriteToLine($file_name, $i, "", 1)
        $success = True
        ExitLoop
    EndIf
Next
if $success = True Then
    MsgBox(0, "Success", "Line has been deleted")
Else
    MsgBox(0, "Failure", "Line wasn't found")
EndIf

 

Link to post
Share on other sites
  • Moderators

@vin1 That is a great assessment of what you need - but please understand that this is not a forum where you put in an order and someone barfs up code for you. What you haven't provided us with is what you have tried on your own, and what trouble you are running into. Please do so, so we can assist in showing you how to improve your script.

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to post
Share on other sites

Not sure if this is what you meant, I've included two examples, just uncomment out one or the other, if you want to just replace lines with "" then use _Example1() or if you want to remove the lines then use _Example2().

#include <Array.au3>
#Include <File.au3>

Local $aSearchText ;~ Search Items
    _FileReadToArray(@ScriptDir & "\SearchText.txt", $aSearchText)
    If @error Then Exit MsgBox(4096, "Remove List", "Error: Reading SearchText.txt")

;~ Select Folder Path
Global $sFolderPath = FileSelectFolder("Select folder", @ScriptDir)
    If @error Then Exit MsgBox(4096, "Select Folder", "Error: No folder selected.")

;~ Folder Path Txt files to array
Global $aFileList = _FileListToArrayRec($sFolderPath, "*.txt", 1, 0, 0, 2)
    If @error Then Exit MsgBox(4096, "Folder List", "Error: Creating FileList.")

;~ _Example1()
_Example2()

;~ Overwrites lines with blank "" text, does not remove lines.
Func _Example1()
    Local $iLineCount
    ;~ Loop through each File Name
    For $i = 1 To $aFileList[0]
        $iLineCount = _FileCountLines($aFileList[$i])
        ;~ Loop through each file
        For $j = 0 To $iLineCount
            ;~ Loop through Search Text items
            For $k = 1 To $aSearchText[0]
                If StringInStr(FileReadLine($aFileList[$i], $j), $aSearchText[$k]) Then
                    ;~ Overwrite line data
                    _FileWriteToLine($aFileList[$i], $j, "", 1)
                EndIf
            Next
        Next
    Next
EndFunc

;~ Exampe2 Removes Lines from file
Func _Example2()
    Local $aFileRead, $aFindText, $hFileOpen, $bFindText = False
    ;~ Loop through each File Name
    For $i = 1 To $aFileList[0]
        _FileReadToArray($aFileList[$i], $aFileRead)
        If @error Then
            MsgBox(4096, "File Read to Array", "Error: Reading: " & $aFileList[$i] & " & to an Array")
            ContinueLoop
        EndIf
        ;~ Loop through Search Text Array
        For $j = 1 To $aSearchText[0]
            ;~ Find all instances of Search Text item
            $aFindText = _ArrayFindAll($aFileRead, $aSearchText[$j])
            If @error Then ContinueLoop
            ;~ Loop through array and remove lines from the array
            For $k = UBound($aFindText) - 1 To 0 Step - 1
                _ArrayDelete($aFileRead, $aFindText[$k])
                $bFindText = True
            Next
        Next
        ;~ If replacements were made overwrite the file with the updated array data.
        If $bFindText Then
            $hFileOpen = FileOpen($aFileList[$i], 2)
            _FileWriteFromArray($hFileOpen, $aFileRead, 1)
            FileClose($hFileOpen)
            $bFindText = False
        EndIf
    Next
EndFunc

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By MrKm
      AutoIT-OCRSpace-UDF1.3.zip
      This tiny yet powerful UDF will help you to convert Images to text with the help of  OCRSpace API version 3.50 .
      Detect text from a local file.
      ; ========================================================= ; Example 2 : Gets text from an image from a local path reference ; : Searchable PDF is not requested by default. ; : Processes it using a basic OCR logic. ; ========================================================= $b_Create_Searchable_PDF = True ; Use a table logic for receipt OCR $b_Table = True ; Set your key here. $v_OCRSpaceAPIKey = "" $OCROptions = _OCRSpace_SetUpOCR($v_OCRSpaceAPIKey, 1, $b_Table, True, "eng", True, Default, Default, $b_Create_Searchable_PDF) $sText_Detected = _OCRSpace_ImageGetText($OCROptions, @scriptdir & "\receipt.jpg", 0, "SEARCHABLE_URL") ConsoleWrite( _ " Detected text : " & $sText_Detected & @CRLF & _ " Error Returned : " & @error & @CRLF & _ " PDF URL : " & Eval("SEARCHABLE_URL") & @CRLF)  
      Detect text from a URL reference.
      ; ========================================================= ; Example 1 : Gets text from an image using a url reference ; : Searchable PDF is not requested. ; : Processes it using a basic OCR logic. ; ========================================================= $v_OCRSpaceAPIKey = "" ; SetUp some preferences.. $OCROptions = _OCRSpace_SetUpOCR($v_OCRSpaceAPIKey, 1, False, True, "eng", True, Default, Default, False) ; Make the request.. $sText_Detected = _OCRSpace_ImageGetText($OCROptions, "https://i.imgur.com/vbYXwJm.png", 0) ConsoleWrite( _ " Detected text : " & $sText_Detected & @CRLF & _ " Error Returned : " & @error & @CRLF)    
      Detect text from a URL reference to an array
      #include "OCRSpaceUDF\_OCRSpace_UDF.au3" #include <array.au3> ; Set your key here. $v_OCRSpaceAPIKey = "" $OCROptions = _OCRSpace_SetUpOCR($v_OCRSpaceAPIKey, 1, $b_Table, True, "eng", True, Default, Default, False) ; Below, the return type is set to 1 to return an array containing the coordinates of the bounding boxes for each word detected, ; in the format : #WordDetected , #Left , #Top , 3Height, #Width $aText_Detected = _OCRSpace_ImageGetText($OCROptions, "https://i.imgur.com/Z1enogD.jpeg", 1) _ArrayDisplay($aText_Detected, "")  
      Download Latest Version : 
      https://github.com/MurageKabui/AutoIT-OCRSpace-UDF
    • By sg08234
      Members 0   2 10 posts   Posted 1 minute ago I have a littel script:
      AutoItSetOption("MustDeclareVars", 1) #include <AutoItConstants.au3> #include <MsgBoxConstants.au3> Local $iReturn  ; Returnwert Local $iVar     ; Variable Local $iBit     ; Bitnummer $iVar=$Cmdline[2] $iBit=$Cmdline[3] Switch $Cmdline[1]     Case 1         $iReturn=BitOr ($ivar,2^$iBit)     Case 2         $iReturn=BitAnd ($iVar,2^$iBit)         if ($iReturn = 2^$iBit ) Then             $iReturn=0         Else             $iReturn=1         EndIf EndSwitch Exit $iReturn which does bit handling. It works as desired but: If I want to check the Returncode of the EXE created in the calling batch within an if-clause %ERRORLEVEL% does not match the Returncode  of my script (calling outside of an if-clause works as desired).
      My assumption for this behaviour is: I do not use  enabledelayedexpansion  in my batch-system and thus this special "variable" %ERRORLEVEL% is not defined in the if-clause. If my assumption is correct: How can I retransfer the Returncode to batch?
      Thanks - Michael
    • By TTE26
      How can I get a full name for a folder that starts with "data_" and ends with random numbers and characters?
      I want to get a folders name inside Temp Directory.
      Not sure how to even start. 🤭

      Any suggestions? 🤔
    • By CarlD
      List (and, optionally, Delete) 0-byte files in current or specified directory; optionally, recurse through subdirectories.
      The heart of the matter is func _ListZeroByteFiles().
      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Outfile=ListZero.exe #AutoIt3Wrapper_UseUpx=y #AutoIt3Wrapper_Change2CUI=y #AutoIt3Wrapper_AU3Check_Parameters=-w 3 -w 4 -w 5 -w 6 -d #AutoIt3Wrapper_Run_Au3Stripper=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** ; ; List (and, optionally, Delete) Zero-byte Files ; in current|specified directory ; Optionally, recurse through subdirs ; CLD rev. 2021-06-20 ; #cs Usage ----- ListZero d:\path1[ d:\path2 ...] [/R] [/-A] [/V] [/D[R]] /X:exclude_file [/?|/H] d:\path Path(s) to search (at least one is *required*) /R Recurse through subdirectories /-A Omit check for alternative data streams (ADS) /V Verbose: list subdirectory names in addition to files /D Delete listed files (NOT recommended on system drive) /DR Move listed files to Recycle bin /X:exclude_file Exclude files with *extensions* listed in exclude_file (one extension per line) /?|/H Help #ce #include <Misc.au3> #include <WinAPIFiles.au3> Global $sDir = "." Global $bSubDirs = 0, $sMsg = "", $iDeles = 0, $iFiles = 0, $bQuiet = 1 Global $sWinDrive = StringLeft(@WindowsDir, 2), $sTestStr = $sDir Global $vDele = 0, $sDeleWord = "", $sLastWord = "Deleted" Global $sExtFn = "", $aExts, $sExExts = "" Global $bADS = 1, $bNTFS = 0, $iRecurseLimit = 0 ; Test for at least one dir in command Global $p = $CmdLine[0] If $p Then For $i = 1 To $CmdLine[0] If StringInStr($CmdLine[$i], "/") = 1 Then $p -= 1 Next EndIf If $p < 1 Or StringInStr($CmdLineRaw, "/?") Or StringInStr($CmdLineRaw, "/H") Then Exit Consolewrite("List (and, optionally, Delete) Zero-byte Files [CLD rev.2021-02-07]" & @CRLF & @CRLF & StringTrimRight(@ScriptName, 4) & " d:\path1[ d:\path2 ...] [/R] [/-A] [/V] [/D[R]] /X:exclude_file [/?|/H]" & @CRLF & @CRLF & "d:\path Path(s) to search (at least one is *required*)" & @CRLF & "/R Recurse through subdirectories" & @CRLF & "/-A Omit check for alternate data streams (ADS)" & @CRLF & "/V Verbose: list subdirectory names in addition to files" & @CRLF & "/D Delete listed files (NOT recommended on system drive)" & @CRLF & "/DR Move listed files to Recycle bin" & @CRLF & "/X:exclude_file" & @CRLF & " Exclude files with *extensions* listed in exclude_file" & @CRLF & " (one extension per line)" & @CRLF & "/?|/H Help" & @CRLF) If StringInStr($CmdLineRaw, "/R") Then $bSubDirs = 1 If StringInStr($CmdLineRaw, "/-A") Then $bADS = 0 If StringInStr($CmdLineRaw, "/D") Then $vDele = 2 $sDeleWord = "Delet" If StringInStr($CmdLineRaw, "/DR") Then $vDele = 1 $sDeleWord = "Recycl" EndIf $sDeleWord &= "ed ==> " EndIf If StringInStr($CmdLineRaw, "/V") Then $bQuiet = 0 If StringInStr($CmdLineRaw, "/X:") Then $sExtFn = StringTrimLeft($CmdLineRaw, 2 + StringInStr($CmdLineRaw, "/X:")) While StringInStr($sExtFn, " ") = 1 $sExtFn = StringTrimLeft($sExtFn, 1) WEnd If StringInStr($sExtFn, """") = 1 Then $sExtFn = StringTrimLeft($sExtFn, 1) If StringInStr($sExtFn, """") Then $sExtFn = _ StringTrimRight($sExtFn, StringLen($sExtFn) - StringInStr($sExtFn, """")) Else If StringInStr($sExtFn, " ") Then $sExtFn = StringTrimRight($sExtFn, StringLen($sExtFn) - StringInStr($sExtFn, " ")) EndIf If FileExists($sExtFn) Then Global $h1 = FileOpen($sExtFn) $sExExts = FileRead($h1) FileClose($h1) If $sExExts Then If StringInStr($sExExts, @CRLF) Then $aExts = StringSplit($sExExts, @CRLF) $sExExts = "." For $i = 1 To $aExts[0] If $aExts[$i] Then $sExExts &= $aExts[$i] & "." Next Else $sExExts = "." & $sExExts & "." EndIf EndIf EndIf EndIf If $vDele = 2 And StringInStr($CmdLineRaw, $sWinDrive) Then ConsoleWrite("Warning: Deleting zero-byte files in the system drive (" & $sWinDrive & ") is not recommended." & @CRLF & "Are you sure you want to continue? (y|N)" & @CRLF) Global $hDLL = DLLOpen("user32.dll") While 1 If _IsPressed("59", $hDLL) Then ConsoleWrite(@CRLF) ExitLoop ElseIf _IsPressed("1B", $hDLL) Or _IsPressed("4E", $hDLL) Then DLLClose($hDLL) ConsoleWrite(@CRLF & "Quitting..." & @CRLF) Exit Else Sleep(20) EndIf WEnd DLLClose($hDLL) EndIf If $bSubDirs Then ConsoleWrite("Working... (Ctrl+C quits)" & @CRLF) For $i = 1 To $CmdLine[0] If StringInStr($CmdLine[$i], "/") = 1 Then ContinueLoop If $CmdLine[$i - 1] = "/X" Then ContinueLoop If StringRight($CmdLine[$i], 1) <> "\" Then $CmdLine[$i] &= "\" $CmdLine[$i] &= "\" $bNTFS = _SetbNTFS($CmdLine[$i]) $iDeles += _ListZeroByteFiles($CmdLine[$i], $bSubDirs) Next If $vDele = 1 Then $sLastWord = "Recycled" Global $iDiff = 7 + StringLen("Deleted") - StringLen($sLastWord) $sMsg = "Found " & StringFormat("%7s", _IntFormat($iFiles)) & " " & _OneMany("file", $iFiles) & @CRLF & $sLastWord & " " & StringFormat("%" & String($iDiff) & "s", _IntFormat($iDeles)) & " " & _OneMany("file", $iDeles) Exit ConsoleWrite(@CRLF & $sMsg & @CRLF) ;--- Func _ListZeroByteFiles($sPath = ".", $bRecurs = 0) ; List|Delete 0-byte files in current or specified directory ; Optionally, recurse through subdirectories ; Returns number of 0-byte files deleted $iRecurseLimit += 1 If $iRecurseLimit = 200 Then $iRecurseLimit = 0 Return EndIf If StringRight($sPath, 1) <> "\" Then $sPath &= "\" If StringRight($sPath, 1) = "\" Then $sPath &= "*" If Not FileExists($sPath) Then Return 0 Local $sFn = "", $iC = 0, $iC2 = 0, $bEx = 0 Local $sDirName = _FileGetPath($sPath) Local $h = FileFindFirstFile($sPath) If $h = -1 Then Return 0 While 1 $sFn = $sDirName & "\" & FileFindNextFile($h) If @error Then FileClose($h) ExitLoop EndIf $bEx = @extended If StringInStr($sFn, ":") = 2 Then $sFn = StringUpper(StringLeft($sFn, 1)) & StringTrimLeft($sFn, 1) If $bEx = 0 Then; we have a file If _FileGetSizeADS($sFn) = 0 Then If $sExExts Then If StringInStr($sExExts, "." & _FileGetExt($sFn) & ".") Then ContinueLoop EndIf $iFiles += 1 Switch $vDele Case 0 Case 1 If FileRecycle($sFn) Then $iC += 1 Case 2 If FileDelete($sFn) Then $iC += 1 EndSwitch ConsoleWrite($sDeleWord & $sFn & @CRLF) EndIf Else; we have a directory If $bRecurs Then If $bQuiet = 0 Then ConsoleWrite("Searching " & $sFn & @CRLF) $iC2 = _ListZeroByteFiles($sFn, 1) If $iC2 > 0 Then $iC += $iC2 $iC2 = 0 EndIf EndIf WEnd Return $iC EndFunc ;==>_ListZeroByteFiles Func _FileGetExt($sFn) ; Parse ext from [d:\path\]filename.ext Local $sExt = "", $aA If StringInStr($sFn, ".") Then If StringInStr(FileGetAttrib($sFn), "D") Then Return $sExt $aA = StringSplit($sFn, ".") $sExt = $aA[$aA[0]] EndIf Return $sExt EndFunc ;==>_FileGetExt Func _FileGetPath($sFn) ; Parse directory from path\file; final "\" is trimmed Local $sDirr = "" Local $aA = StringSplit($sFn, "\") Local $iS = $aA[0] - 1 If Not StringInStr(FileGetAttrib($aA[$aA[0]]), "D") Then $iS += 1 For $i = 1 To $iS $sDirr &= $aA[$i] & "\" Next While StringRight($sDirr, 1) = "\" $sDirr = StringTrimRight($sDirr, 1) WEnd Return $sDirr EndFunc ;==>_FileGetPath Func _FileGetSizeADS($sFile) Local $sErrW, $sFnTmp, $aFnTmp Local $iSize = FileGetSize($sFile) If Not ($bADS And $bNTFS) Then Return $iSize $iSize = 0 Local $pData = _WinAPI_CreateBuffer(1024) Local $tFSD = DllStructCreate($tagWIN32_FIND_STREAM_DATA) Local $hSearch = _WinAPI_FindFirstStream($sFile, $tFSD) While Not @error $iSize += DllStructGetData($tFSD, 'StreamSize') _WinAPI_FindNextStream($hSearch, $tFSD) WEnd Switch @extended Case 38 ; ERROR_HANDLE_EOF Case Else $sErrW = _WinAPI_GetErrorMessage(@extended) $aFnTmp = StringSplit($sFile, "\") $sFnTmp = $aFnTmp[$aFnTmp[0]] If Not StringRight($sErrW, 13) = "successfully." Then _ ConsoleWrite("--> " & $sFnTmp & ": " & $sErrW & @CRLF) EndSwitch _WinAPI_FindClose($hSearch) _WinAPI_FreeMemory($pData) Return $iSize EndFunc ;==>_FileGetSizeADS Func _IntFormat($n, $s = ",", $sd = ".") ; Insert commas|specified separator into integer If StringIsInt($n) Then Local $a, $d = "", $x If StringInStr($n, $sd) Then $a = StringSplit($n, $sd) $n = $a[1] $d = $sd & $a[2] EndIf $x = $n $n = "" While StringLen($x) > 3 $n = $s & StringRight($x, 3) & $n $x = StringTrimRight($x, 3) WEnd $n = $x & $n EndIf Return ($n & $d) EndFunc ;==>_IntFormat Func _OneMany($sSingular, $iCount, $sPlural = "") ; Returns singular or plural depending on count ; Plural appends S to singular (ES if it ends in S) ; unless $sPlural is supplied Local $sEss = "s" If StringRight($sSingular, 1) = "s" Then $sEss = "es" If StringUpper($sSingular) == $sSingular Then $sEss = StringUpper($sEss) If Not $sPlural Then $sPlural = $sSingular & $sEss If Abs($iCount) = 1 Then Return $sSingular Else Return $sPlural EndIf EndFunc ;==>_OneMany Func _SetbNTFS($sPath) If DriveGetFileSystem(StringLeft($sPath, 3)) = "NTFS" Then Return 1 Else Return 0 EndIf EndFunc ;==>_SetbNTFS  
    • By lIlIIlIllIIIIlI
      $input = $CmdLine[1] $bytes = 1000000 ; 1000000 for 1 MB, 1000 for 1 KB $size = FileGetSize($input) $file = fileopen($input, 16) $max = ceiling($size / $bytes) for $i = 1 to $max $data = fileread($file, $bytes) $output = $input & '_' & $i & 'of' & $max filewrite($output, $data) next ^file split
      file path for a 20MB "video.mp4" is input, it will be output as "video.mp4_1of20", "video.mp4_2of20", etc. change $bytes to affect the split files size, this example made them 1MB (10^6 bytes)
       
      $input = $CmdLine[1] $name = stringtrimright($input, 1 + stringlen($input) - stringinstr($input, '_', 0, -1)) $split = stringsplit($input, 'of', 3) $max = $split[ubound($split) - 1] for $i = 1 to $max $in = $name & '_' & $i & 'of' & $max $file = fileopen($in, 16) $data = fileread($file) fileclose($file) filedelete($in) filewrite($name, $data) next ^ file join
      file path for any of the "video.mp4_Xof20" segments is input. the "video.mp4_Xof20" segments are read and written to "video.mp4" and then deleted, leaving the newly joined "video.mp4" in the end
       
      i made this today because i had a big file that i couldn't really open. i split it into 1000 chunks to make processing and stuff easier. i've also used it to split files to just under 25MB segments so i can attach and mail big files over gmail which is silly but it worked
×
×
  • Create New...