Jump to content

Problem with _ReplaceStringInFile


GoogleDude
 Share

Recommended Posts

I am not sure why the below sample is not making any changes to my file? I think its becuase its replacing the old data with the same new data and not appending what I realy need to change which is the path.

#include <File.au3>
#NoTrayIcon
$New_Path = @ScriptDir & '\Test' & '\Subfolder'
$FileToEdit = "c:\test.txt"
$TextToSearchFor = "Load File "
$TextToReplaceWith = "Load File"
$MoreText = $New_Path
_ReplaceStringInFile($FileToEdit, $TextToSearchFor, $TextToReplaceWith & '"' & $MoreText & '"')
Exit

Can the whole of text be replaced and not just the charecters? I dont want it to append the new text in front or behind of the old text.

So the updated output should be something like below

The original file looks like below

Load File "W:\New Folder\Test\Tester"

And the new changed file Should look like below.

Load File "G:\Test\Subfolder"

Regards,

GoogleDude

Edited by GoogleDude
Link to comment
Share on other sites

I am not sure why the below sample is not making any changes to my file? I think its becuase its replacing the old data with the same new data and not appending what I realy need to change which is the path.

Can the whole of text be replaced and not just the charecters? I dont want it to append the new text in front or behind of the old text.

So the updated output should be something like below

The original file looks like below

Load File "W:\New Folder\Test\Tester"

And the new changed file Should look like below.

Load File "G:\Test\Subfolder"
What you want to do is read the entire file into a single string, then do StringRegExpReplace() and overwrite the string back to the file. Alas, my RegExp Fu is too weak for this task. You are looking for a RegExp that will replace the text "after 'Load File' and between the next two double quotes".

Others on this forum with mighty RegExp Fu skills will surely come to our aid...

:)

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

Well I was kinda able to get it working. It inserts the new path into the correct field but the old data gets moved to the right.

So

File Load = "C:\Windows\System32\test.ini"

becomes

File Load = "H:\Test\USB\test.ini""C:\Windows\System32\test.ini"

GoogleDude

Cool! That's pretty close. Did you do that with a RegExp? If so, post it for tweaking. I'll bet it's just one change to make it overwrite instead of appending the selection.

P.S. And the 990 lines is nowhere near too big to operate on in memory.

:)

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

  • Moderators

Calling all AutoIters with mad RegExp Fu skills. :)

I looked at RegExp in Help but I dont understand how it can be used. Im still trying to learn AutoIt. I know it is a simple change.

GoogleDude

http://perldoc.perl.org/perlre.html#Regular-Expressions

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

Here is why you're getting this result: File Load = "H:\Test\USB\test.ini""C:\Windows\System32\test.ini"

because you're replacing "File Load" with File Load = "H:\Test\USB\test.ini"

So in order to make it work you will need to replace

$TextToSearchFor = "File Load ""C:\Windows\System32\test.ini"""

$TextToReplaceWith = "Load File"

I have to say that I'm quite confused about how your script will work - in the actual form it will replace the IDENTICAL 900 lines with another IDENTICAL 900 lines .... but that's your choice.

here is the working version:

#include <File.au3>
#NoTrayIcon
$New_Path = @ScriptDir & '\Test' & '\Subfolder'
$FileToEdit = "c:\test.txt"
$TextToSearchFor = "Load File ""W:\New Folder\Test\Tester"""
$TextToReplaceWith = "Load File "
$MoreText = $New_Path
_ReplaceStringInFile($FileToEdit, $TextToSearchFor, $TextToReplaceWith & """" & $MoreText & """")
Exit

Good luck,

SNMP_UDF ... for SNMPv1 and v2c so far, GetBulk and a new example script

wannabe "Unbeatable" Tic-Tac-Toe

Paper-Scissor-Rock ... try to beat it anyway :)

Link to comment
Share on other sites

Here is why you're getting this result: File Load = "H:\Test\USB\test.ini""C:\Windows\System32\test.ini"

here is the working version:

#include <File.au3>
#NoTrayIcon
$New_Path = @ScriptDir & '\Test' & '\Subfolder'
$FileToEdit = "c:\test.txt"
$TextToSearchFor = "Load File ""W:\New Folder\Test\Tester"""
$TextToReplaceWith = "Load File "
$MoreText = $New_Path
_ReplaceStringInFile($FileToEdit, $TextToSearchFor, $TextToReplaceWith & """" & $MoreText & """")
Exit

Good luck,

In your sample above you have the $TextToSearchFor and $TextToReplaceWith swapped and the actual path is dynamic (usb drive) so it will always be something diff.???????? So setting the $TextToSearhFor will be hard to set as a var.

Edited by GoogleDude
Link to comment
Share on other sites

I don't know what are you up to and right now I couldn't care less ...

I showed you where you were wrong (why were you getting your results) and I make your original code to work.

... sometimes I wonder why I spend my time trying to help people ...

SNMP_UDF ... for SNMPv1 and v2c so far, GetBulk and a new example script

wannabe "Unbeatable" Tic-Tac-Toe

Paper-Scissor-Rock ... try to beat it anyway :)

Link to comment
Share on other sites

Sorry for confusing the situation more than needed. Since I am not a coder by trade and AutoIt is really the only (other than English) programming language I know. So I have a lot to learn from it. I have found that most of the rather simple functions are easy to pick up on and such. And there are some areas/parts of AutoIt I have not yet dove into (yet). A wife, 5 kids, and job, take most of my time up. So I get very little time to really tear into it as much as I would like.

None-the-less. I am able to get it to replace it with what I am after but am unable to get it or replace make it NOT append the new data before the old data but rather replace the whole line? Thats what I still dont understand?

For what its worth. I am trying to make Apache Web Server,PHP, and MySQL (Portable/USB) usable via a systray Icon. I know there are a few other portable versions out there such as WOS (Webserver On a Stick) ect.. But to hopefully improve my AutoIt skills its a small project I am working on. Just so I can say I did it.

The file I am editing is the httpd.conf that has path reference in it, I want to replace the old path entries with the path of the source media such as USB/CD, ect...

Hope this clears it up. Or even matters any more.

Thanks again for the assistance.

GoogleDude

Link to comment
Share on other sites

Post your httpd.conf file here and I might be able to help. Also try to explain what exactly do you want to change (post a small part of your original file and another part of the file the way you want it to be). - do you want to keep a part of the original path and to change only the begining (drive letter and initial folder)?

I'm pretty sure that it can be done without any RegExp stuff once you find the pattern.

SNMP_UDF ... for SNMPv1 and v2c so far, GetBulk and a new example script

wannabe "Unbeatable" Tic-Tac-Toe

Paper-Scissor-Rock ... try to beat it anyway :)

Link to comment
Share on other sites

IPB will not let me upload a httpd.conf file so I posted the contents of it below. I have already taken care of switching the \'s with /'s so im good there. But basicly I want to replace lines 69,76,140,141 with news path names from the location of there the compiled script is launched from. I have this location set as a $var already.

Below is Before My systray app is loaded.

LoadModule php5_module "D:/AutoIt Scripts/WebServer/php5/php5apache2.dll"

and this is httpd.conf after I have loaded my Systray app.

LoadModule php5_module "N:/WebServer/php5/php5apache2.dll"

This is the whole httpd.conf file.

Thanks again for the help. Believe it or not I do appreciate it much.

PidFile logs/httpd.pid
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule mpm_winnt.c>
ThreadsPerChild 250
MaxRequestsPerChild  0
</IfModule>
Listen 80
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dir_module modules/mod_dir.so
LoadModule env_module modules/mod_env.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
LoadModule isapi_module modules/mod_isapi.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule mime_module modules/mod_mime.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule userdir_module modules/mod_userdir.so
ServerAdmin admin@localhost
ServerName localhost:80
UseCanonicalName Off
DocumentRoot "D:/AutoIt Scripts/WebServer/www"
<Directory "D:/AutoIt Scripts/WebServer/www">
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory "D:/AutoIt Scripts/WebServer/www">
    Options Indexes FollowSymLinks
    AllowOverride All
</Directory>
UserDir "My Documents/My Website"
DirectoryIndex index.html index.html.var index.htm index.php index.php4 index.php3 index.php4
AccessFileName .htaccess
<FilesMatch "^\.ht">
    Order allow,deny
    Deny from all
</FilesMatch>
TypesConfig conf/mime.types
DefaultType text/plain
<IfModule mod_mime_magic.c>
    MIMEMagicFile conf/magic
</IfModule>
HostnameLookups Off
ErrorLog logs/error.log
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
CustomLog logs/access.log common
ServerTokens Full
ServerSignature On
<Directory "D:/AutoIt Scripts/WebServer/www">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
ScriptAlias /cgi-bin/
<Directory "D:/AutoIt Scripts/WebServer/www">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>
IndexOptions FancyIndexing VersionSort
AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip
AddIconByType (TXT,/icons/text.gif) text/*
AddIconByType (IMG,/icons/image2.gif) image/*
AddIconByType (SND,/icons/sound2.gif) audio/*
AddIconByType (VID,/icons/movie.gif) video/*
ReadmeName README.html
HeaderName HEADER.html
IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t
AddLanguage en .en
LanguagePriority en
ForceLanguagePriority Prefer Fallback
AddCharset ISO-8859-1  .iso8859-1 .latin1
AddCharset ISO-8859-2  .iso8859-2 .latin2 .cen
AddCharset ISO-8859-3  .iso8859-3 .latin3
AddCharset ISO-8859-4  .iso8859-4 .latin4
AddCharset ISO-8859-5  .iso8859-5 .latin5 .cyr .iso-ru
AddCharset ISO-8859-6  .iso8859-6 .latin6 .arb
AddCharset ISO-8859-7  .iso8859-7 .latin7 .grk
AddCharset ISO-8859-8  .iso8859-8 .latin8 .heb
AddCharset ISO-8859-9  .iso8859-9 .latin9 .trk
AddCharset ISO-2022-JP .iso2022-jp .jis
AddCharset ISO-2022-KR .iso2022-kr .kis
AddCharset ISO-2022-CN .iso2022-cn .cis
AddCharset Big5     .Big5      .big5
AddCharset WINDOWS-1251 .cp-1251   .win-1251
AddCharset CP866       .cp866
AddCharset KOI8-r     .koi8-r .koi8-ru
AddCharset KOI8-ru   .koi8-uk .ua
AddCharset ISO-10646-UCS-2 .ucs2
AddCharset ISO-10646-UCS-4 .ucs4
AddCharset UTF-8       .utf8
AddCharset GB2312     .gb2312 .gb 
AddCharset utf-7       .utf7
AddCharset utf-8       .utf8
AddCharset big5     .big5 .b5
AddCharset EUC-TW     .euc-tw
AddCharset EUC-JP     .euc-jp
AddCharset EUC-KR     .euc-kr
AddCharset shift_jis   .sjis
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddHandler type-map var
BrowserMatch "Mozilla/2" nokeepalive
BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0
BrowserMatch "RealPlayer 4\.0" force-response-1.0
BrowserMatch "Java/1\.0" force-response-1.0
BrowserMatch "JDK/1\.0" force-response-1.0
BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
BrowserMatch "MS FrontPage" redirect-carefully
BrowserMatch "^WebDrive" redirect-carefully
BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully
BrowserMatch "^gnome-vfs" redirect-carefully
BrowserMatch "^XML Spy" redirect-carefully
BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully
<IfModule mod_ssl.c>
    Include conf/ssl.conf
</IfModule>
LoadModule php5_module "D:/AutoIt Scripts/WebServer/php5/php5apache2.dll"
PHPIniDir "D:/AutoIt Scripts/WebServer/php5/"
AddType application/x-httpd-php .php .php4 .php5 .php3
Edited by GoogleDude
Link to comment
Share on other sites

From what do I see here you are looking to replace the first part of the path (replace D:/AutoIt Scripts with N:/ because the rest of the path is identical)

Let's try to modify your original script to reflect this:

#include <File.au3>
#NoTrayIcon
$New_Path = @ScriptDir & '\Test' & '\Subfolder'
$FileToEdit = "c:\test.txt"
$TextToSearchFor = "D:/AutoIt Scripts/"
$TextToReplaceWith = "N:/"
_ReplaceStringInFile($FileToEdit, $TextToSearchFor, $TextToReplaceWith)
Exit

This is doing that exact replacement and it is your first script having only modified what to replace. :)

Hope this helps.

SNMP_UDF ... for SNMPv1 and v2c so far, GetBulk and a new example script

wannabe "Unbeatable" Tic-Tac-Toe

Paper-Scissor-Rock ... try to beat it anyway :)

Link to comment
Share on other sites

Would it be posible to replace a whole string even if the strings length is dynamic? I can get it to place the string in I need but it does not replace the old string it just inserts it into the beginning of the line, and since the line will be dynamic it is hard to do this.

Edited by GoogleDude
Link to comment
Share on other sites

I don't know why but I have a "bad feeling" about this.

You keep saying that you cannot replace the string but it is added ... I don't know why you're not able to replace the string YET - I've showed you that it is a matter of what to search and what to replace.

Please post your whole code here because right now I have no idea what's inside and what you're trying to do.

Try to "rephrase" what you want your code to do.

Do you want your code to replace - as I said - the first part of the path? Do you know what that part will be? Do you know everytime the new path?

Anyway - I spent 1 hour to make this - and it takes care of whatever the initial path is as long as the constant part starts at "/WebServer..."

#include <GUIConstants.au3>
#include <File.au3>

Opt("GUIOnEventMode", 1)
#Region ### START Koda GUI section ### Form=
$Form1 = GUICreate("Form1", 315, 153, 193, 125)
GUISetOnEvent($GUI_EVENT_CLOSE, "Form1Close")
$Input1 = GUICtrlCreateInput("Old Path", 16, 24, 201, 21)
$Input2 = GUICtrlCreateInput("New Path", 15, 64, 201, 21)
$Button2 = GUICtrlCreateButton("Browse", 232, 64, 65, 25, 0)
GUICtrlSetOnEvent(-1, "Button2Click")
$Button3 = GUICtrlCreateButton("Replace", 50, 112, 90, 25, 0)
GUICtrlSetOnEvent(-1, "Button3Click")
$Button3 = GUICtrlCreateButton("Refresh", 180, 112, 50, 25, 0)
GUICtrlSetOnEvent(-1, "refresh")
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###
Dim $search = ""
Dim $new_path
refresh()


While 1
    Sleep(100)
WEnd

Func refresh()
    $test = FileOpen("C:\test.txt", 0)
    For $i=1 to FileGetSize("C:\test.txt")
        $string = FileReadLine($test, $i)
        If StringInStr($string, ":/") Then          ;looks for ":/" which is a pattern for begining of path
            $pos = StringInStr($string, ":/") - 2   ;determine the position of the letter drive
            $search = StringTrimLeft($string, $pos) ;trim the left part of the string
            $pos_end = StringInStr($search, "/Web")-1       ;determine the end position
            $search = StringTrimRight($search, StringLen ($search) - $pos_end)      ;trim the right part
            GUICtrlSetData($Input1, $search)        ;update the field
            ExitLoop
        EndIf
    Next
    FileClose($test)
EndFunc

Func Button2Click()
    $new_path = FileSelectFolder ( "Select the DESTINATION Folder", "",7 )  ;select the new folder
    $new_path = StringReplace($new_path, "\", "/")
    GUICtrlSetData($Input2, $new_path)
EndFunc

Func Button3Click()
    $FileToEdit = "c:\test.txt"
    $TextToSearchFor = $search
    $TextToReplaceWith = $new_path
    _ReplaceStringInFile($FileToEdit, $TextToSearchFor, $TextToReplaceWith)
    MsgBox(0, "Job Done", "All paths replaced")
EndFunc

Func Form1Close()
    Exit
EndFunc

SNMP_UDF ... for SNMPv1 and v2c so far, GetBulk and a new example script

wannabe "Unbeatable" Tic-Tac-Toe

Paper-Scissor-Rock ... try to beat it anyway :)

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...