Jump to content

Look for substring within string...if found replace it?


Recommended Posts

Hey!

I have a text file (text_file.txt) containing data as so:

substring:replacement

bye:hello
no:yes

Basically a list of two words/phrases seperated by the : character. (the first is the substring to look for, the other is the replacement) - each pair is on a new line.

Now what I want to do is somehow extract the text files data and loop through it (atleast thats how I'd do so in PHP), so it looks for the substring within the $string and if found replaces it with the replacement so e.g. if bye is found within the $string, then its replaced with hello.

My current code:

;this is where its going to be applying the replacements too...
$string = '.....';

;extract the text files data...
$text_file_data = FileRead(@ScriptDir & "\text_file.txt")

Hope that makes sense, I'm fairly new to Autoit and I'm used to using PHP (as you may have noticed from the way I thought out the process :x)

Appreciate all your help!

Edited by newbtophpautoit
Link to comment
Share on other sites

  • Moderators

newbtophpautoit,

I would read the text of the file you wish to alter into a single variable (FileRead) and the list of pairs into an array (_FileReadToArray).

I would then loop through the pairs list (For...Next) and split each pair into the target and replacement (StringSplit) - once you have those 2 words, replace all instances of the former with the latter in the file text (StringReplace).

Finally rewrite the altered file (FileWrite). :x

Give it a go - you know where we are if you run into problems. :P

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Sounded like a fun demo, and I'm waiting for some long scripts to run.

Test1.txt:

good:bad
aid:legislature
quick:lazy
jumped:crawled
over:under

Test1.au3:

#include <File.au3>

Global $aReplace
Global $sFile = @ScriptDir & "\Test1.txt"
Global $sString = "Now is the time for all good men to come to the aid of their country.  The quick brown fox jumped over the lazy dog."

ConsoleWrite("Debug: $sString = " & $sString & @LF)

_FileReadToArray($sFile, $aReplace)
For $n = 1 To $aReplace[0]
    $aSplit = StringSplit($aReplace[$n], ":")
    $sString = StringReplace($sString, $aSplit[1], $aSplit[2])
Next

ConsoleWrite("Debug: $sString = " & $sString & @LF)

Missing all kinds of boring stuff like error checking and correction for replacing capitalized words, etc.

Merry Christmas!

:x

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
Link to comment
Share on other sites

newbtophpautoit,

I would read the text of the file you wish to alter into a single variable (FileRead) and the list of pairs into an array (_FileReadToArray).

I would then loop through the pairs list (For...Next) and split each pair into the target and replacement (StringSplit) - once you have those 2 words, replace all instances of the former with the latter in the file text (StringReplace).

Finally rewrite the altered file (FileWrite). :x

Give it a go - you know where we are if you run into problems. :shifty:

M23

Cool! I'll give it a go, Autoit seems pretty similiar to PHP.

StringReplace => str_replace()

for => for()

StringSplit => implode()

and so on :P

Edited by newbtophpautoit
Link to comment
Share on other sites

Sounded like a fun demo, and I'm waiting for some long scripts to run.

Test1.txt:

good:bad
aid:legislature
quick:lazy
jumped:crawled
over:under

Test1.au3:

#include <File.au3>

Global $aReplace
Global $sFile = @ScriptDir & "\Test1.txt"
Global $sString = "Now is the time for all good men to come to the aid of their country.  The quick brown fox jumped over the lazy dog."

ConsoleWrite("Debug: $sString = " & $sString & @LF)

_FileReadToArray($sFile, $aReplace)
For $n = 1 To $aReplace[0]
    $aSplit = StringSplit($aReplace[$n], ":")
    $sString = StringReplace($sString, $aSplit[1], $aSplit[2])
Next

ConsoleWrite("Debug: $sString = " & $sString & @LF)

Missing all kinds of boring stuff like error checking and correction for replacing capitalized words, etc.

Merry Christmas!

:x

Snap! thats how I also did it however I use $aRecords instead of $aReplace (just copyied from documentation :P)

and Merry Christmas!

Link to comment
Share on other sites

  • Moderators

newbtophpautoit,

Glad we could help. But in future, when you reply please use the "Add Reply" button at the top and bottom of the page rather then the "Reply" button in the post itself. That way you do not get the contents of the previous post quoted in your reply and the whole thread becomes easier to read. :x

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

I try to avoid using useless UDF functions if possible so here is the same thing as Melba23 wanted you to do sans the file.au3 UDF

$sDoc = @ScriptDir & "\somefile.txt"
$sStr = FileRead($sDoc)
$sHold = $sStr
$aSRE = StringRegExp(FileRead(@ScriptDir & "\Text_File.txt", "(?m:^|\n)(.+):(.+)", 3)
If NOT @Error Then
    For $i = 0 To Ubound($aSRE) -2 Step 2
        $sStr = StringReplace($sStr, $aSRE[$i], $aSRE[$i+1])
    Next
EndIf
If $sStr <> $sHold Then
    $hFile = FileOpen($sDoc, 2)
    FileWrite($hFile, $sStr)
    FileClose($hFile)
EndIf
Edited by GEOSoft

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...