topbanner_forum
  *

avatar image

Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  • Saturday December 14, 2024, 5:06 pm
  • Proudly celebrating 15+ years online.
  • Donate now to become a lifetime supporting member of the site and get a non-expiring license key for all of our programs.
  • donate

Author Topic: Frep - commandline find and replace  (Read 7143 times)

justice

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 1,898
    • View Profile
    • Donate to Member
Frep - commandline find and replace
« on: August 02, 2010, 04:22 AM »
Needed a small utility to use in batch files to find and replace text in a file.
Code: Autohotkey [Select]
  1. #NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
  2. SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
  3. TheFile = %1%
  4. TheSearch = %2%
  5. TheReplace = %3%
  6. if 0 < 3
  7. {
  8.     MsgBox This script requires at least 3 incoming parameters but it only received %0%.
  9.     ExitApp
  10. }
  11. FileRead, Contents, %TheFile%
  12. StringReplace, Contents, Contents, %TheSearch%, %TheReplace%, A
  13. FileDelete, %TheFile%
  14. FileAppend, %Contents%,  %TheFile%
  15. Contents =

An example:
>type test.txt
greg is a lovely guy
>frep test.txt greg john
>type test.txt
john is a lovely guy

I'm using it for a tiny templating engine for CSS files ;)
« Last Edit: August 02, 2010, 04:25 AM by justice »

Tuxman

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 2,508
    • View Profile
    • Donate to Member
Re: Frep - commandline find and replace
« Reply #1 on: August 02, 2010, 11:06 PM »
Now why don't you use sed instead?  8)

justice

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 1,898
    • View Profile
    • Donate to Member
Re: Frep - commandline find and replace
« Reply #2 on: August 03, 2010, 05:21 AM »
Because I don't know the sed syntax and it was more fun to write a script that works how I expect it should work :) Could someone move this to the finished snacks section please? :)

rjbull

  • Charter Member
  • Joined in 2005
  • ***
  • default avatar
  • Posts: 3,205
    • View Profile
    • Donate to Member
Re: Frep - commandline find and replace
« Reply #3 on: August 04, 2010, 04:16 PM »
For once I agree with Tuxman   8)  Though I used AWK more because AWK scripts are easier to maintain.  Another option is Minitrue by Andrew Pipkin, which is specifically designed for the job.  It's worth reading Eric Pement's sed page for more details on this; keep paging down to the "related batch editing files" section which mentions Minitrue amongst others.  On no account overlook Mr. Pement's supplementary page on Minitrue workarounds.  Mr. Pement appears unaware that Jason Hood has made an updated version of MiniTrue that fixes some issues, though I haven't tried it.