Find and replace with regex (Batch .BAT)

2019-05-20 06:01发布

问题:

I want to do a find/replace in several textfiles. How to automatize this with a .BAT ? (I also need regular expressions)

Example : Look for :

<ObjectList ObjectType="MyObject">
(anything here)
</ObjectList>

Then delete this text and replace by :

<ObjectList ObjectType="MyNewObject">
Blablabla
Blablabla
</ObjectList>

How to do this with a .BAT script ?

EDIT : I have lots of file to find/replace, and some of them are not XML. So I would need a general solution... What is the most simple way to do it (I don't want to install a third part software). VBS or BATCH ? If someone has a very small example code, thanks a lot in advance! Thanks!

回答1:

Use regular expressions via the VBScript.RegExp class of VBScript.

For example:

@ECHO OFF
(
    ECHO Set Regex = CreateObject^("VBScript.RegExp"^)
    ECHO Regex.Pattern = "[E-G]$"
    ECHO MsgBox^(Regex.Replace^("A B C D E", "X"^)^)
) > Regex.vbs
CSCRIPT //NOLOGO Regex.vbs
DEL Regex.vbs
PAUSE > NUL

The code above would show the message "A B C D X".

I hope that I have helped.



回答2:

Since you're manipulating XML, I'd use something XML-specific to maintain encodings, entities etc.

Check out XMLStarlet for a command-line based XML toolset, and in particular the ed command which allows you to edit documents.

xml ed --help
XMLStarlet Toolkit: Edit XML document(s)
Usage: xml ed <global-options> {<action>} [ <xml-file-or-uri> ... ]
where
  <global-options>  - global options for editing
  <xml-file-or-uri> - input XML document file name/uri (stdin is used if missing)

<global-options> are:
  -P (or --pf)        - preserve original formatting
  -S (or --ps)        - preserve non-significant spaces
  -O (or --omit-decl) - omit XML declaration (<?xml ...?>)
  -N <name>=<value>   - predefine namespaces (name without 'xmlns:')
                        ex: xsql=urn:oracle-xsql
                        Multiple -N options are allowed.
                        -N options must be last global options.
  --help or -h        - display help

where <action>
   -d or --delete <xpath>
   -i or --insert <xpath> -t (--type) elem|text|attr -n <name> -v (--value) <value>
   -a or --append <xpath> -t (--type) elem|text|attr -n <name> -v (--value) <value>
   -s or --subnode <xpath> -t (--type) elem|text|attr -n <name> -v (--value) <value>
   -m or --move <xpath1> <xpath2>
   -r or --rename <xpath1> -v <new-name>
   -u or --update <xpath> -v (--value) <value>
              -x (--expr) <xpath> (-x is not implemented yet)