Regex Replace from Command line

81,206

Solution 1

go here
http://gnuwin32.sourceforge.net/packages.html
scroll down to SED. Download coreutils too while you're at it.

this command will replace a with b globally, and on each line. so not just the first occurrence on the line.

e.g. using sed "s/a/b/g" a.txt

C:\>type a.txt
aaaa
aaa

C:\>sed "s/a/b/" a.txt
baaa
baa

C:\>sed "s/a/b/g" a.txt
bbbb
bbb

C:\>

VBScript does support regular expressions, you can do find and replace with it.

dim re, s
set re = new RegExp

re.Pattern="in"
re.Global=True 'false is default
s="bin din in"
MsgBox re.Replace(s,"xxx")

Displays bxxx dxxx xxx

Solution 2

The Scripting Guy covers how to do this in PowerShell (no additional downloads on most recent Windows OSs, you probably already have it installed).

Start it up, run the following (to replace a * with a @):

(Get-Content C:\Scripts\Test.txt) | 
Foreach-Object {$_ -replace "\*", "@"} | 
Set-Content C:\Scripts\Test.txt

This supports .NET regular expressions, including positive and negative look-ahead, and all manner of things notepad++ did not support with regex before version 6.x (as much as I love notepad++).

Solution 3

I've found fnr.exe for that. It has GUI and command-line.

An open source tool to find and replace text in multiple files.

Features

  • Single file download - fnr.exe (127kb)
  • Replace text in multiple files using windows application or through command line
  • Find Only to see where matches are found
  • Case-sensitive searching
  • Searching for files in one directory or recursing sub-directories
  • Regular expressions
  • Find and replace multi-line text
  • Generate command line button to create command line text to put in batch file
  • Command line help
  • Unit tests of Find/Replace engine

Viewing command line options

enter image description here

Solution 4

I'm a little late to the party, but JREPL.BAT is a hybrid JScript/batch script based regex utility that runs natively on any Windows machine from XP onward.

Full documentation is built into the script, which can be accessed via JREPL /?, or use JREPL /?? for paged output.

JREPL uses standard ECMA regex that comes with JScript. ECMA regex is not quite as powerful as the .NET regex available to powershell, but it is still pretty darn good. And I think the average user will find this utility easier to use than powershell.

The built-in JREPL options already provide a lot of inherent power, but the ability to inject user supplied JScript really opens up amazing possibilities.

I developed the script because my workplace does not allow downloading of non-standard exe files, but has no restriction on writing batch or JScript scripts :-)

Simply follow the link and copy the script code into a file named JREPL.BAT. Read the subsequent posts from that thread for examples of usage and development history. There are also many StackOverflow answers that use JREPL.BAT.

Solution 5

Looks like you can use regex with FINDSTR

findstr [Windows CMD]:

findstr allows to search for text (as specified with pattern in the file file-name. If file-name contains wildcards (* or ?), it searches in all files that match. The option /S searches in the current directory as well as in its subdirectories. If pattern contains spaces, it must be specified like so /C:"some text to be searched". In order to turn pattern into a regular expressions, the /R option must be used. The /I option searches case insensitive.

From FindStr's Help (Findstr /?):

/R - Uses search strings as regular expressions.

Regular expression quick reference:
  .        Wildcard: any character
  *        Repeat: zero or more occurrences of previous character or class
  ^        Line position: beginning of line
  $        Line position: end of line
  [class]  Character class: any one character in set
  [^class] Inverse class: any one character not in set
  [x-y]    Range: any characters within the specified range
  \x       Escape: literal use of metacharacter x
  \<xyz    Word position: beginning of word
  xyz\>    Word position: end of word
Share:
81,206
Aziz
Author by

Aziz

Updated on September 18, 2022

Comments

  • Aziz
    Aziz over 1 year

    Is it possible to regex replace from command line? Right now I'm using notepad++ to do this. In command line I can only use FINDSTR wich can only locate the mached files/lines

    EDIT :
    Maybe it will be possible to make a VB script and run it from cmd? I just created a file "hi.vbs" with the content

    Msgbox "Hi Buddy"
    

    Then cmd allows me to run it directly by typing "hi" from command line.
    So if it is not possible with batch script, then i may use a VB script trough batch. Or..?

  • Aziz
    Aziz over 12 years
    Thank you for your answer, but this was not my question.
  • Aziz
    Aziz over 12 years
    Amazing crazy tool!!! This tool was too adwanced. I could not manage to use it yet, but when I read gnu.org/software/sed/manual/sed.html#The-_0022s_0022-Command I can see that this can do much more than what I could expect. Thanks a lot
  • Aziz
    Aziz over 12 years
    Thank you JRobert for your suggestion. Sorry that I did not understod it, but now I can see that SED was the thing.
  • tvdo
    tvdo over 10 years
    Notepad++ supports full PCRE as of version 6.
  • sarh
    sarh almost 9 years
    Pretty nice - you can check your "find" statement in GUI, click "Gen Replace Command Line" and get ready to use command line call. No need to spend time to get familiar with command line syntax.
  • barlop
    barlop almost 9 years
    and re what vtest said, in case anybody doesn't know. cygwin has bash.
  • G-.
    G-. over 8 years
    I couldn't manage to get this to exit after making the changes. I have to press enter to close making this not especially useful for scripting
  • Sergius
    Sergius over 8 years
    @G-. There is no waiting for <enter> if it is run from a batch file.
  • kofifus
    kofifus about 8 years
    sed sucks with multi-line replaces though
  • barlop
    barlop about 8 years
    @kofifus I know you know this sentence, but just for the sake of others and clarifying what you are saying - doing a search/replace on multiple lines sed's fine for, as it operates on each line, but where the search string spans across multiple lines, yeah, sed isn't designed for that(since as mentioned, it operates on each line). One can use perl.see my answer here for some examples superuser.com/questions/416419/… or probably any language with regex support, though perl is the mother of them.
  • Rick
    Rick over 7 years
    I couldn't find a way to output to a different filename/extension
  • Kenny Evitt
    Kenny Evitt over 7 years
    Neither sed nor perl work well (or at least easily) with Unicode (especially UTF-16) on Windows.
  • Kenny Evitt
    Kenny Evitt over 7 years
    findstr can't replace text in files!
  • barlop
    barlop over 7 years
    @KennyEvitt cmd shell requires a tweak to get it to display and use of chcp for unicode utf8 chcp 65001 (as you say, utf16 encoding.chcp 1200 and chcp 12001 is not supported) stackoverflow.com/questions/9321419/… Not sure re mintty. Not sure re powershell. But utf-8 is supported ok in cmd or powershell. So long as a supporting font is used like courier new, and so long as it's codepage 65001. There is a cmd /u for a utf16 encoding.
  • barlop
    barlop about 6 years
    @barlop as of 2018, gnuwin32 is now also old.. cygwin is more up to date!
  • Sergei Krivonos
    Sergei Krivonos almost 6 years
    +1 sed shipped with git