Windows find and replace in files

I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to d...

Note — Be sure to see the update at the end of this answer for a link to the superior JREPL.BAT that supersedes REPL.BAT
JREPL.BAT 7.0 and above natively supports unicode (UTF-16LE) via the /UTF option, as well as any other character set, including UTF-8, via ADO!!!!


I have written a small hybrid JScript/batch utility called REPL.BAT that is very convenient for modifying ASCII (or extended ASCII) files via the command line or a batch file. The purely native script does not require installation of any 3rd party executeable, and it works on any modern Windows version from XP onward. It is also very fast, especially when compared to pure batch solutions.

REPL.BAT simply reads stdin, performs a JScript regex search and replace, and writes the result to stdout.

Here is a trivial example of how to replace foo with bar in test.txt, assuming REPL.BAT is in your current folder, or better yet, somewhere within your PATH:

type test.txt|repl "foo" "bar" >test.txt.new
move /y test.txt.new test.txt

The JScript regex capabilities make it very powerful, especially the ability of the replacement text to reference captured substrings from the search text.

I’ve included a number of options in the utility that make it quite powerful. For example, combining the M and X options enable modification of binary files! The M Multi-line option allows searches across multiple lines. The X eXtended substitution pattern option provides escape sequences that enable inclusion of any binary value in the replacement text.

The entire utility could have been written as pure JScript, but the hybrid batch file eliminates the need to explicitly specify CSCRIPT every time you want to use the utility.

Here is the REPL.BAT script. Full documentation is embedded within the script.

@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment

::************ Documentation ***********
::REPL.BAT version 6.2
:::
:::REPL  Search  Replace  [Options  [SourceVar]]
:::REPL  /?[REGEX|REPLACE]
:::REPL  /V
:::
:::  Performs a global regular expression search and replace operation on
:::  each line of input from stdin and prints the result to stdout.
:::
:::  Each parameter may be optionally enclosed by double quotes. The double
:::  quotes are not considered part of the argument. The quotes are required
:::  if the parameter contains a batch token delimiter like space, tab, comma,
:::  semicolon. The quotes should also be used if the argument contains a
:::  batch special character like &, |, etc. so that the special character
:::  does not need to be escaped with ^.
:::
:::  If called with a single argument of /?, then prints help documentation
:::  to stdout. If a single argument of /?REGEX, then opens up Microsoft's
:::  JScript regular expression documentation within your browser. If a single
:::  argument of /?REPLACE, then opens up Microsoft's JScript REPLACE
:::  documentation within your browser.
:::
:::  If called with a single argument of /V, case insensitive, then prints
:::  the version of REPL.BAT.
:::
:::  Search  - By default, this is a case sensitive JScript (ECMA) regular
:::            expression expressed as a string.
:::
:::            JScript regex syntax documentation is available at
:::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
:::  Replace - By default, this is the string to be used as a replacement for
:::            each found search expression. Full support is provided for
:::            substituion patterns available to the JScript replace method.
:::
:::            For example, $& represents the portion of the source that matched
:::            the entire search pattern, $1 represents the first captured
:::            submatch, $2 the second captured submatch, etc. A $ literal
:::            can be escaped as $$.
:::
:::            An empty replacement string must be represented as "".
:::
:::            Replace substitution pattern syntax is fully documented at
:::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
:::  Options - An optional string of characters used to alter the behavior
:::            of REPL. The option characters are case insensitive, and may
:::            appear in any order.
:::
:::            A - Only print altered lines. Unaltered lines are discarded.
:::                If the S options is present, then prints the result only if
:::                there was a change anywhere in the string. The A option is
:::                incompatible with the M option unless the S option is present.
:::
:::            B - The Search must match the beginning of a line.
:::                Mostly used with literal searches.
:::
:::            E - The Search must match the end of a line.
:::                Mostly used with literal searches.
:::
:::            I - Makes the search case-insensitive.
:::
:::            J - The Replace argument represents a JScript expression.
:::                The expression may access an array like arguments object
:::                named $. However, $ is not a true array object.
:::
:::                The $.length property contains the total number of arguments
:::                available. The $.length value is equal to n+3, where n is the
:::                number of capturing left parentheses within the Search string.
:::
:::                $[0] is the substring that matched the Search,
:::                $[1] through $[n] are the captured submatch strings,
:::                $[n+1] is the offset where the match occurred, and
:::                $[n+2] is the original source string.
:::
:::                Arguments $[0] through $[10] may be abbreviated as
:::                $1 through $10. Argument $[11] and above must use the square
:::                bracket notation.
:::
:::            L - The Search is treated as a string literal instead of a
:::                regular expression. Also, all $ found in the Replace string
:::                are treated as $ literals.
:::
:::            M - Multi-line mode. The entire contents of stdin is read and
:::                processed in one pass instead of line by line, thus enabling
:::                search for n. This also enables preservation of the original
:::                line terminators. If the M option is not present, then every
:::                printed line is terminated with carriage return and line feed.
:::                The M option is incompatible with the A option unless the S
:::                option is also present.
:::
:::                Note: If working with binary data containing NULL bytes,
:::                      then the M option must be used.
:::
:::            S - The source is read from an environment variable instead of
:::                from stdin. The name of the source environment variable is
:::                specified in the next argument after the option string. Without
:::                the M option, ^ anchors the beginning of the string, and $ the
:::                end of the string. With the M option, ^ anchors the beginning
:::                of a line, and $ the end of a line.
:::
:::            V - Search and Replace represent the name of environment
:::                variables that contain the respective values. An undefined
:::                variable is treated as an empty string.
:::
:::            X - Enables extended substitution pattern syntax with support
:::                for the following escape sequences within the Replace string:
:::
:::                \     -  Backslash
:::                b     -  Backspace
:::                f     -  Formfeed
:::                n     -  Newline
:::                q     -  Quote
:::                r     -  Carriage Return
:::                t     -  Horizontal Tab
:::                v     -  Vertical Tab
:::                xnn   -  Extended ASCII byte code expressed as 2 hex digits
:::                unnnn -  Unicode character expressed as 4 hex digits
:::
:::                Also enables the q escape sequence for the Search string.
:::                The other escape sequences are already standard for a regular
:::                expression Search string.
:::
:::                Also modifies the behavior of xnn in the Search string to work
:::                properly with extended ASCII byte codes.
:::
:::                Extended escape sequences are supported even when the L option
:::                is used. Both Search and Replace support all of the extended
:::                escape sequences if both the X and L opions are combined.
:::
:::  Return Codes:  0 = At least one change was made
:::                     or the /? or /V option was used
:::
:::                 1 = No change was made
:::
:::                 2 = Invalid call syntax or incompatible options
:::
:::                 3 = JScript runtime error, typically due to invalid regex
:::
::: REPL.BAT was written by Dave Benham, with assistance from DosTips user Aacini
::: to get xnn to work properly with extended ASCII byte codes. Also assistance
::: from DosTips user penpen diagnosing issues reading NULL bytes, along with a
::: workaround. REPL.BAT was originally posted at:
::: http://www.dostips.com/forum/viewtopic.php?f=3&t=3855
:::

::************ Batch portion ***********
@echo off
if .%2 equ . (
  if "%~1" equ "/?" (
    <"%~f0" cscript //E:JScript //nologo "%~f0" "^:::" "" a
    exit /b 0
  ) else if /i "%~1" equ "/?regex" (
    explorer "http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx"
    exit /b 0
  ) else if /i "%~1" equ "/?replace" (
    explorer "http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx"
    exit /b 0
  ) else if /i "%~1" equ "/V" (
    <"%~f0" cscript //E:JScript //nologo "%~f0" "^::(REPL.BAT version)" "$1" a
    exit /b 0
  ) else (
    call :err "Insufficient arguments"
    exit /b 2
  )
)
echo(%~3|findstr /i "[^SMILEBVXAJ]" >nul && (
  call :err "Invalid option(s)"
  exit /b 2
)
echo(%~3|findstr /i "M"|findstr /i "A"|findstr /vi "S" >nul && (
  call :err "Incompatible options"
  exit /b 2
)
cscript //E:JScript //nologo "%~f0" %*
exit /b %errorlevel%

:err
>&2 echo ERROR: %~1. Use REPL /? to get help.
exit /b

************* JScript portion **********/
var rtn=1;
try {
  var env=WScript.CreateObject("WScript.Shell").Environment("Process");
  var args=WScript.Arguments;
  var search=args.Item(0);
  var replace=args.Item(1);
  var options="g";
  if (args.length>2) options+=args.Item(2).toLowerCase();
  var multi=(options.indexOf("m")>=0);
  var alterations=(options.indexOf("a")>=0);
  if (alterations) options=options.replace(/a/g,"");
  var srcVar=(options.indexOf("s")>=0);
  if (srcVar) options=options.replace(/s/g,"");
  var jexpr=(options.indexOf("j")>=0);
  if (jexpr) options=options.replace(/j/g,"");
  if (options.indexOf("v")>=0) {
    options=options.replace(/v/g,"");
    search=env(search);
    replace=env(replace);
  }
  if (options.indexOf("x")>=0) {
    options=options.replace(/x/g,"");
    if (!jexpr) {
      replace=replace.replace(/\\/g,"\B");
      replace=replace.replace(/\q/g,""");
      replace=replace.replace(/\x80/g,"\u20AC");
      replace=replace.replace(/\x82/g,"\u201A");
      replace=replace.replace(/\x83/g,"\u0192");
      replace=replace.replace(/\x84/g,"\u201E");
      replace=replace.replace(/\x85/g,"\u2026");
      replace=replace.replace(/\x86/g,"\u2020");
      replace=replace.replace(/\x87/g,"\u2021");
      replace=replace.replace(/\x88/g,"\u02C6");
      replace=replace.replace(/\x89/g,"\u2030");
      replace=replace.replace(/\x8[aA]/g,"\u0160");
      replace=replace.replace(/\x8[bB]/g,"\u2039");
      replace=replace.replace(/\x8[cC]/g,"\u0152");
      replace=replace.replace(/\x8[eE]/g,"\u017D");
      replace=replace.replace(/\x91/g,"\u2018");
      replace=replace.replace(/\x92/g,"\u2019");
      replace=replace.replace(/\x93/g,"\u201C");
      replace=replace.replace(/\x94/g,"\u201D");
      replace=replace.replace(/\x95/g,"\u2022");
      replace=replace.replace(/\x96/g,"\u2013");
      replace=replace.replace(/\x97/g,"\u2014");
      replace=replace.replace(/\x98/g,"\u02DC");
      replace=replace.replace(/\x99/g,"\u2122");
      replace=replace.replace(/\x9[aA]/g,"\u0161");
      replace=replace.replace(/\x9[bB]/g,"\u203A");
      replace=replace.replace(/\x9[cC]/g,"\u0153");
      replace=replace.replace(/\x9[dD]/g,"\u009D");
      replace=replace.replace(/\x9[eE]/g,"\u017E");
      replace=replace.replace(/\x9[fF]/g,"\u0178");
      replace=replace.replace(/\b/g,"b");
      replace=replace.replace(/\f/g,"f");
      replace=replace.replace(/\n/g,"n");
      replace=replace.replace(/\r/g,"r");
      replace=replace.replace(/\t/g,"t");
      replace=replace.replace(/\v/g,"v");
      replace=replace.replace(/\x[0-9a-fA-F]{2}|\u[0-9a-fA-F]{4}/g,
        function($0,$1,$2){
          return String.fromCharCode(parseInt("0x"+$0.substring(2)));
        }
      );
      replace=replace.replace(/\B/g,"\");
    }
    search=search.replace(/\\/g,"\B");
    search=search.replace(/\q/g,""");
    search=search.replace(/\x80/g,"\u20AC");
    search=search.replace(/\x82/g,"\u201A");
    search=search.replace(/\x83/g,"\u0192");
    search=search.replace(/\x84/g,"\u201E");
    search=search.replace(/\x85/g,"\u2026");
    search=search.replace(/\x86/g,"\u2020");
    search=search.replace(/\x87/g,"\u2021");
    search=search.replace(/\x88/g,"\u02C6");
    search=search.replace(/\x89/g,"\u2030");
    search=search.replace(/\x8[aA]/g,"\u0160");
    search=search.replace(/\x8[bB]/g,"\u2039");
    search=search.replace(/\x8[cC]/g,"\u0152");
    search=search.replace(/\x8[eE]/g,"\u017D");
    search=search.replace(/\x91/g,"\u2018");
    search=search.replace(/\x92/g,"\u2019");
    search=search.replace(/\x93/g,"\u201C");
    search=search.replace(/\x94/g,"\u201D");
    search=search.replace(/\x95/g,"\u2022");
    search=search.replace(/\x96/g,"\u2013");
    search=search.replace(/\x97/g,"\u2014");
    search=search.replace(/\x98/g,"\u02DC");
    search=search.replace(/\x99/g,"\u2122");
    search=search.replace(/\x9[aA]/g,"\u0161");
    search=search.replace(/\x9[bB]/g,"\u203A");
    search=search.replace(/\x9[cC]/g,"\u0153");
    search=search.replace(/\x9[dD]/g,"\u009D");
    search=search.replace(/\x9[eE]/g,"\u017E");
    search=search.replace(/\x9[fF]/g,"\u0178");
    if (options.indexOf("l")>=0) {
      search=search.replace(/\b/g,"b");
      search=search.replace(/\f/g,"f");
      search=search.replace(/\n/g,"n");
      search=search.replace(/\r/g,"r");
      search=search.replace(/\t/g,"t");
      search=search.replace(/\v/g,"v");
      search=search.replace(/\x[0-9a-fA-F]{2}|\u[0-9a-fA-F]{4}/g,
        function($0,$1,$2){
          return String.fromCharCode(parseInt("0x"+$0.substring(2)));
        }
      );
      search=search.replace(/\B/g,"\");
    } else search=search.replace(/\B/g,"\\");
  }
  if (options.indexOf("l")>=0) {
    options=options.replace(/l/g,"");
    search=search.replace(/([.^$*+?()[{\|])/g,"\$1");
    if (!jexpr) replace=replace.replace(/$/g,"$$$$");
  }
  if (options.indexOf("b")>=0) {
    options=options.replace(/b/g,"");
    search="^"+search
  }
  if (options.indexOf("e")>=0) {
    options=options.replace(/e/g,"");
    search=search+"$"
  }
  var search=new RegExp(search,options);
  var str1, str2;

  if (srcVar) {
    str1=env(args.Item(3));
    str2=str1.replace(search,jexpr?replFunc:replace);
    if (!alterations || str1!=str2) if (multi) {
      WScript.Stdout.Write(str2);
    } else {
      WScript.Stdout.WriteLine(str2);
    }
    if (str1!=str2) rtn=0;
  } else if (multi){
    var buf=1024;
    str1="";
    while (!WScript.StdIn.AtEndOfStream) {
      str1+=WScript.StdIn.Read(buf);
      buf*=2
    }
    str2=str1.replace(search,jexpr?replFunc:replace);
    WScript.Stdout.Write(str2);
    if (str1!=str2) rtn=0;
  } else {
    while (!WScript.StdIn.AtEndOfStream) {
      str1=WScript.StdIn.ReadLine();
      str2=str1.replace(search,jexpr?replFunc:replace);
      if (!alterations || str1!=str2) WScript.Stdout.WriteLine(str2);
      if (str1!=str2) rtn=0;
    }
  }
} catch(e) {
  WScript.Stderr.WriteLine("JScript runtime error: "+e.message);
  rtn=3;
}
WScript.Quit(rtn);

function replFunc($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) {
  var $=arguments;
  return(eval(replace));
}

IMPORTANT UPDATE

I have ceased development of REPL.BAT, and replaced it with JREPL.BAT. This newer utility has all the same functionality of REPL.BAT, plus much more:

  • Unicode UTF-16LE support via native CSCRIPT unicode capabilities, and any other character set (including UTF-8) via ADO.
  • Read directly from / write directly to a file: no need for pipes, redirection, or move command.
  • Incorporate user supplied JScript
  • Translation facility similar to unix tr, only it also supports regex search and JScript replace
  • Discard non-matching text
  • Prefix output lines with line number
  • and more…

As always, full documentation is embedded within the script.

The original trivial solution is now even simpler:

jrepl "foo" "bar" /f test.txt /o -

The current version of JREPL.BAT is available at DosTips. Read all of the subsequent posts in the thread to see examples of usage and a history of the development.

I’m hoping someone might lend their time in helping me create a batch file or similar for finding and replacing text in several files.
I have tried many “search and replace” utilities but have not found something that does what I need.

The requirements are as follows:
Find and replace the SAME text in multiple files with different text FOR EACH FILE.

Example:

File1.txt, file2.txt, file3.txt all have a text string “change me please”

for file1.txt replace text string “change me please” to “file1 changed” save as original filename (file1.txt)
for file2.txt replace text string “change me please” to “file2 changed” save as original filename (file2.txt)
for file3.txt replace text string “change me please” to “file3 changed” save as original filename (file3.txt)

Hennes's user avatar

Hennes

64.3k7 gold badges110 silver badges165 bronze badges

asked Aug 12, 2011 at 6:58

1

Using PowerShell commands:

Get-Content c:file1.txt | ForEach-Object { $_ -replace "change me please", "file1 changed" } | Set-Content c:changed1.txt

Get-Content c:file2.txt | ForEach-Object { $_ -replace "change me please", "file2 changed" } | Set-Content c:changed2.txt

leaves me with the 2 files:

changed1.txt

changed2.txt

Could some kind person tell me how I would then rename these files and overwrite the originals:

changed1.txt to file1.txt

changed2.txt to file2.txt

sblair's user avatar

sblair

12.6k6 gold badges47 silver badges77 bronze badges

answered Aug 12, 2011 at 8:39

pckeys's user avatar

0

Powergrep can do what you ask.

answered Aug 12, 2011 at 7:36

HS.'s user avatar

HS.HS.

1111 gold badge1 silver badge2 bronze badges

2

If the files are not too big then you can use

$filenames = @("file1.txt", "file2.txt", "file3.txt")

foreach ($file in $filenames) 
{
    $replacementStr = $file + ' changed' 
    (Get-Content $file) | 
        Foreach-object { $_ -replace 'change me please' , $replacementStr   } | 
     Set-Content $file
}

Note the brackets around (Get-Content $ file) which means the file is read into memory (hence the requirements that the files are small), but this means that you the file is no longer in use when you go to write it back.

if the files are too big for memory you can write it to a temporary file and then use something like

Cp $tempfilename $file 
rm $tempfilename

to copy the temporary file over the original and delete the temporary file.

answered Aug 12, 2011 at 9:14

sgmoore's user avatar

sgmooresgmoore

6,3332 gold badges24 silver badges32 bronze badges

I found an issue with your script. Having $replacementStr = $file + ‘ changed’ adds the sting $file to the changed file. It should be: $replacementStr = ‘ changed’

I modified this for my own purposes, but now the files names are dynamic, the string is changed correctly, and paths are not broken.

Don’t forget to run this first…Set-ExecutionPolicy RemoteSigned

Code follows:

$filenames = @(get-childitem -Path "C:Program FilesTivoliTSMbaclient*.opt" | % { $_.FullName })

        foreach ($file in $filenames) 
        {
            $replacementStr = 'New String' 
            (Get-Content $file) | 
                Foreach-object { $_ -replace 'Old String' , $replacementStr   } | 
             Set-Content $file
             Write-Host Processed $file
        }

JW

answered Nov 6, 2015 at 15:17

Jennifer Wagner's user avatar

perl -p -i -e 's/change me please/$argv changed/' file1 file2 subdir/*.txt foo/*.xyz

You can download Perl (for Windows) from Activestate or Strawberry etc

answered Aug 12, 2011 at 9:17

RedGrittyBrick's user avatar

RedGrittyBrickRedGrittyBrick

80.6k19 gold badges132 silver badges201 bronze badges

You can use eclipse — simply load the files into a project, the follow the instructions on the following page:

http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html?page=1

Basically do a search on the folder containing the files. The results will show up in a search tab. Right click on the file containing the files you want to change and select ‘Replace’.

This will change all the files you want. Added bonus of having your files in an eclipse project, which can be helpful in many different ways. (Source control, syntax highlighting, unit testing, etc, etc.)

answered Feb 14, 2013 at 17:22

Justin's user avatar

JustinJustin

1113 bronze badges

Open multiple files in Notepad++ and can find/replace across all open files.

answered Apr 29, 2016 at 17:51

Icineflix.com's user avatar

1

Updated: 12/31/2020 by

Finding and replacing text within a text file can be done using any text editor. Below is a listing of all the major text editors with information on how to replace text.

Replacing text within Notepad

Microsoft Notepad is included with all versions of Windows and can replace text in plain text files. To replace text in Notepad, follow the steps below.

  1. Open the text file in Notepad.
  2. Click Edit on the menu bar, then select Replace in the Edit menu.
  3. Once in the Search and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options section for further information and help.

Tip

Press the keyboard shortcut key Ctrl+H to open the Replace window.

Note

The Replace feature in Notepad is limited. If you need to do more than only replace words, consider a different editor.

Replacing text with WordPad

Microsoft WordPad logo

Microsoft WordPad is included with all versions of Windows and can replace text in plain text files. To replace text in WordPad, follow the steps below.

  1. Open the text file in WordPad.
  2. In the Ribbon menu, on the Home tab (shown below), click the Replace option.
  3. In the Search and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.

Tip

Press the keyboard shortcut key Ctrl+H to open the Replace window.

Note

The Replace feature in WordPad is limited. If you need to do more than only replace words, consider a different editor.

Replacing text in Microsoft Word

To replace text in Microsoft Word, follow the steps below.

  1. Open the text file in Microsoft Word.
  2. In the Ribbon menu, on the Home tab, click the Replace option.
  3. In the Find and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.

Find and Replace in Microsoft Word

Tip

Press the keyboard shortcut key Ctrl+H to open the Replace window.

Tip

Clicking the More button in the Find and Replace window gives additional Search Options as shown in the above picture.

Replacing text with Notepad++

Notepad++ is a powerful free and open-source text editor that supports more options for finding and replacing text than any of the above suggestions. To replace text in Notepad++, follow the steps below.

  1. Open the text file in Notepad++.
  2. In the top menu bar, click Search and select Replace.
  3. In the Replace window, on the Replace tab, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.

Tip

Press the keyboard shortcut key Ctrl+H to open the Replace window.

Replacing text in TextPad

Although not free for the full program, TextPad is another fantastic text editor with powerful search and replace features. To replace text in TextPad, follow the steps below.

  1. Open the text file in TextPad.
  2. In the top menu, click Search and then Replace.
  3. In the Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.

Tip

Press the F8 key to open the Replace window.

Find and replace text in Excel

Tip

The Ctrl+F and Command+F keyboard shortcut keys also work in Microsoft Excel and other spreadsheet programs to open the Find and Replace text box.

Microsoft Excel Find and Select

In Microsoft Excel, older versions featured the Edit menu, and the Replace option is found in that menu. Newer versions of Excel feature a Ribbon menu, and the Find & Select option is found on the Home tab, at the far right side as shown in the picture.

Once the shortcut key opens or you click the Replace option under Find & Select, a Find and Replace window opens. On the Replace tab, enter the text you want to find and replace in the spreadsheet.

Using Search and Replace and advanced options

After understanding the above basics on how to open the search and replace features, understanding all the capabilities possible can make your searches even more efficient.

The basics

All the replace options have the two basic features shown below.

  • Match case makes the search case-sensitive, which is useful for finding searches like Names.
  • Match whole word matches the whole search instead of words containing the word. For example, a search for ‘can’ only matches ‘can’ and would not match ‘cannot’ or scan’ in your file.

Wildcard and regular expressions

Programs like Microsoft Word that support wildcards and programs like Notepad++ and TextPad that support regular expressions help perform a search for almost anything imaginable. For example, using regular expressions you can replace text found at the beginning of a line, end of the line, works containing a certain amount of characters, and anything else you need.

Other advanced options

More advanced programs may have the features mentioned below. If your program does not include one of the features below, you need to consider switching programs with these features.

  • Use wildcards is a feature found in Word that lets you use wildcards.
  • Regular expression is the most powerful feature for finding and replacing text in a file.
  • Sounds like (English) is a Word feature to match English sounding words. For example, searching for «color» would find «colour» in your document.
  • Match prefix is a Word feature to match the prefix (beginning) of a word.
  • Match suffix is a Word feature to match the suffix (end) of a word.
  • Ignore punctuation characters is a Word feature to ignore punctuation marks like the single quote in «don’t.»
  • Ignore white space characters is a Word feature to ignore spaces in words.

Download PC Repair Tool to quickly find & fix Windows errors automatically

Sometimes we need to find and replace text in more than one file. The problem begins when we try to do so after opening each file. Certainly, you need only a couple of seconds to find and replace text in two or three files. However, just imagine that you have fifty files and you need to find and replace three words in each file. How do you handle that? Don’t panic. Here is a simple free tool for Windows and this is called Find and Replace Tool. This portable software can find and replace text in multiple files within moments.

Find and Replace Text in Multiple Files

First, download Find and Replace Tool and open it. As this is portable software, you will not have to install it. After opening Find and Replace Tool, the following screen will appear,

The UI is uncluttered. Therefore, you will understand each and every option very quickly. However, just follow the following steps to find and replace text in multiple files using this free tool.

Find and Replace Text in Multiple Files

First, you need to select the Directory, where all the raw files are positioned. It will replace text in those files, which are placed in one folder.

Therefore, to select the directory, just click on the box next to the empty box and choose a directory. After that, write down the particular file extension.

By default, it shows *.*. This means that it will replace text in all files. However, suppose, you want to find and replace text in all .css files. To do so, just enter *.css

If you want to add multiple extensions, add them like this:

*.css,*.php,*.txt

On the other hand, if you want to include all files except .exe and similar. To exclude particular extension, just enter the following in the Exclude Mask section,

*.exe

Or,

*.exe,*.dll

After that, you need to enter the text in the Find box. You can enter either a single word or a line.

In the next step, write down the text you would like to replace with. After completing all, the window will look like this:

Add Words to Replace

Now, you have two options. First, you can hit the Replace button to replace that text immediately. Second, you can get a command that you need to use through Command Prompt to get the same thing. You will get a command in the Command Use box, and the command looks like this:

"C:UsersSudipDownloadsProgramsfnr.exe" --cl --dir "C:UsersSudipDesktopgenesis" --fileMask "*.php,*.css" --excludeFileMask "*.dll, *.exe" --includeSubDirectories --find "genesis" --replace "sudip"

Here, C:UsersSudipDownloadsProgramsfnr.exe is the Find and Replace Tool directory and C:UsersSudipDesktopgenesis is the directory, where all my files are placed.

*.php,*.css are the included file extensions.

*.dll, *.exe are the excluded file extensions.

I have searched genesis and replaced it with sudip.
Get Command to replace text

Just copy the command and paste it in your Command Prompt. After executing the command, you will get a message similar to this:

Find and Replace text using Command prompt

That’s’ it!

If you like it, you can download it from here.

Ezoic

Sudip loves to engage with the latest technology & gadgets. Apart from writing about all things technology, he is a Photoshop junkie and a football enthusiast.

Я пишу командный файл script с использованием командной строки Windows и хочу изменить каждое вхождение какого-либо текста в файл (например, «FOO» ) другим (например, «BAR» ). Каков самый простой способ сделать это? Любые встроенные функции?

4b9b3361

Ответ 1

Многие ответы здесь помогли мне указать верное направление, однако ни один из них не подошел для меня, поэтому я публикую свое решение.

У меня Windows 7, которая поставляется со встроенным PowerShell. Вот скрипт, который я использовал для поиска/замены всех экземпляров текста в файле:

powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"

Чтобы объяснить это:

  • powershell запускает powershell.exe, входящий в состав Windows 7
  • -Command "... " — аргумент командной строки для powershell.exe, содержащий команду для запуска
  • (gc myFile.txt) читает содержимое myFile.txt (gc — сокращение от команды Get-Content)
  • -replace 'foo', 'bar' просто запускает команду замены, чтобы заменить foo на bar
  • | Out-File myFile.txt | Out-File myFile.txt вывод в файл myFile.txt
  • -encoding ASCII позволяет транскрибировать выходной файл в Unicode, как отмечают комментарии

Powershell.exe уже должен быть частью вашего оператора PATH, но если нет, вы можете добавить его. Его расположение на моей машине: C:WINDOWSsystem32WindowsPowerShellv1.0

Ответ 2

Если вы используете версию Windows, поддерживающую .NET, я бы заменил вашу оболочку. PowerShell дает вам полную мощность .Net из командной строки. В нем также много команд. Пример ниже поможет решить ваш вопрос. Я использую полные имена команд, есть более короткие псевдонимы, но это дает вам что-то для Google.

(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt

Ответ 3

Просто используется FART ( « F ind A nd R eplace T ext» утилита командной строки):
отличное небольшое бесплатное ПО для замены текста в большом наборе файлов.

Файлы настроек находятся на SourceForge.

Пример использования:

fart.exe -p -r -c -- C:toolsperl-5.8.9* @@[email protected]@ C:tools

проведет предварительный просмотр замещений, чтобы сделать рекурсивно в файлах этого дистрибутива Perl.

Только проблема: значок веб-сайта FART не совсем со вкусом, утончен или элегантен;)


Обновление 2017 (7 лет спустя) jagb указывает в комментариях к статье 2011 года » FARTing the Easy Way — найти и заменить текст» из Mikail Tunç

Ответ 4

Заменить — заменить подстроку с помощью замены строки
Описание: Чтобы заменить подстроку другой строкой, используйте функцию подстановки строк. Показанный здесь пример заменяет все вхождения «тех» орфографических ошибок с «the» в строковой переменной str.

set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%

Script Выход:

teh cat in teh hat
the cat in the hat

ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

Ответ 5

Создать файл replace.vbs:

Const ForReading = 1    
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText  'WriteLine adds extra CR/LF
objFile.Close

Чтобы использовать этот измененный script (который хорошо вызывает replace.vbs), просто введите в командной строке команду, похожую на это:

cscript replace.vbs "C:ScriptsText.txt" "Jim " "James "

Ответ 6

BatchSubstitute.bat на dostips.com является примером поиска и замены с использованием чистого командного файла.

Он использует комбинацию FOR, FIND и CALL SET.

Линии, содержащие символы среди "&<>]|^, могут обрабатываться некорректно.


Ответ 7

Примечание. Обязательно просмотрите обновление в конце этого ответа для ссылки на главный JREPL.BAT, который заменяет REPL.BAT
JREPL.BAT 7.0 и выше поддерживает Unicode (UTF-16LE) через опцию /UTF, а также любой другой набор символов, включая UTF-8, через ADO !!!!


Я написал небольшую гибридную JScript/пакетную утилиту REPL.BAT, которая очень удобна для изменения файлов ASCII (или расширенных ASCII) через командную строку или командный файл. Чистый собственный скрипт не требует установки любого стороннего исполняемого файла, и он работает с любой современной версией Windows с XP. Это также очень быстро, особенно по сравнению с чистыми пакетными решениями.

REPL.BAT просто читает stdin, выполняет поиск и замену регулярного выражения JScript и записывает результат в stdout.

Вот тривиальный пример того, как заменить foo на bar в test.txt, если REPL.BAT находится в вашей текущей папке или, еще лучше, где-то внутри вашего PATH:

type test.txt|repl "foo" "bar" >test.txt.new
move /y test.txt.new test.txt

Возможности регулярного выражения JScript делают его очень мощным, особенно способность заменяющего текста ссылаться на захваченные подстроки из текста поиска.

Я включил ряд опций в утилиту, которые делают ее достаточно мощной. Например, объединение опций M и X позволяет изменять бинарные файлы! Параметр M Multi-line позволяет выполнять поиск по нескольким строкам. Параметр X eXtended substitution pattern предоставляет escape-последовательности, которые позволяют включить любое двоичное значение в заменяющий текст.

Вся утилита могла быть написана как чистый JScript, но гибридный пакетный файл устраняет необходимость явно указывать CSCRIPT каждый раз, когда вы хотите использовать эту утилиту.

Вот сценарий REPL.BAT. Полная документация встроена в скрипт.

@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment

::************ Documentation ***********
::REPL.BAT version 6.2
:::
:::REPL  Search  Replace  [Options  [SourceVar]]
:::REPL  /?[REGEX|REPLACE]
:::REPL  /V
:::
:::  Performs a global regular expression search and replace operation on
:::  each line of input from stdin and prints the result to stdout.
:::
:::  Each parameter may be optionally enclosed by double quotes. The double
:::  quotes are not considered part of the argument. The quotes are required
:::  if the parameter contains a batch token delimiter like space, tab, comma,
:::  semicolon. The quotes should also be used if the argument contains a
:::  batch special character like &, |, etc. so that the special character
:::  does not need to be escaped with ^.
:::
:::  If called with a single argument of /?, then prints help documentation
:::  to stdout. If a single argument of /?REGEX, then opens up Microsoft's
:::  JScript regular expression documentation within your browser. If a single
:::  argument of /?REPLACE, then opens up Microsoft JScript REPLACE
:::  documentation within your browser.
:::
:::  If called with a single argument of /V, case insensitive, then prints
:::  the version of REPL.BAT.
:::
:::  Search  - By default, this is a case sensitive JScript (ECMA) regular
:::            expression expressed as a string.
:::
:::            JScript regex syntax documentation is available at
:::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
:::  Replace - By default, this is the string to be used as a replacement for
:::            each found search expression. Full support is provided for
:::            substituion patterns available to the JScript replace method.
:::
:::            For example, $& represents the portion of the source that matched
:::            the entire search pattern, $1 represents the first captured
:::            submatch, $2 the second captured submatch, etc. A $ literal
:::            can be escaped as $$.
:::
:::            An empty replacement string must be represented as "".
:::
:::            Replace substitution pattern syntax is fully documented at
:::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
:::  Options - An optional string of characters used to alter the behavior
:::            of REPL. The option characters are case insensitive, and may
:::            appear in any order.
:::
:::            A - Only print altered lines. Unaltered lines are discarded.
:::                If the S options is present, then prints the result only if
:::                there was a change anywhere in the string. The A option is
:::                incompatible with the M option unless the S option is present.
:::
:::            B - The Search must match the beginning of a line.
:::                Mostly used with literal searches.
:::
:::            E - The Search must match the end of a line.
:::                Mostly used with literal searches.
:::
:::            I - Makes the search case-insensitive.
:::
:::            J - The Replace argument represents a JScript expression.
:::                The expression may access an array like arguments object
:::                named $. However, $ is not a true array object.
:::
:::                The $.length property contains the total number of arguments
:::                available. The $.length value is equal to n+3, where n is the
:::                number of capturing left parentheses within the Search string.
:::
:::                $[0] is the substring that matched the Search,
:::                $[1] through $[n] are the captured submatch strings,
:::                $[n+1] is the offset where the match occurred, and
:::                $[n+2] is the original source string.
:::
:::                Arguments $[0] through $[10] may be abbreviated as
:::                $1 through $10. Argument $[11] and above must use the square
:::                bracket notation.
:::
:::            L - The Search is treated as a string literal instead of a
:::                regular expression. Also, all $ found in the Replace string
:::                are treated as $ literals.
:::
:::            M - Multi-line mode. The entire contents of stdin is read and
:::                processed in one pass instead of line by line, thus enabling
:::                search for n. This also enables preservation of the original
:::                line terminators. If the M option is not present, then every
:::                printed line is terminated with carriage return and line feed.
:::                The M option is incompatible with the A option unless the S
:::                option is also present.
:::
:::                Note: If working with binary data containing NULL bytes,
:::                      then the M option must be used.
:::
:::            S - The source is read from an environment variable instead of
:::                from stdin. The name of the source environment variable is
:::                specified in the next argument after the option string. Without
:::                the M option, ^ anchors the beginning of the string, and $ the
:::                end of the string. With the M option, ^ anchors the beginning
:::                of a line, and $ the end of a line.
:::
:::            V - Search and Replace represent the name of environment
:::                variables that contain the respective values. An undefined
:::                variable is treated as an empty string.
:::
:::            X - Enables extended substitution pattern syntax with support
:::                for the following escape sequences within the Replace string:
:::
:::                \     -  Backslash
:::                b     -  Backspace
:::                f     -  Formfeed
:::                n     -  Newline
:::                q     -  Quote
:::                r     -  Carriage Return
:::                t     -  Horizontal Tab
:::                v     -  Vertical Tab
:::                xnn   -  Extended ASCII byte code expressed as 2 hex digits
:::                unnnn -  Unicode character expressed as 4 hex digits
:::
:::                Also enables the q escape sequence for the Search string.
:::                The other escape sequences are already standard for a regular
:::                expression Search string.
:::
:::                Also modifies the behavior of xnn in the Search string to work
:::                properly with extended ASCII byte codes.
:::
:::                Extended escape sequences are supported even when the L option
:::                is used. Both Search and Replace support all of the extended
:::                escape sequences if both the X and L opions are combined.
:::
:::  Return Codes:  0 = At least one change was made
:::                     or the /? or /V option was used
:::
:::                 1 = No change was made
:::
:::                 2 = Invalid call syntax or incompatible options
:::
:::                 3 = JScript runtime error, typically due to invalid regex
:::
::: REPL.BAT was written by Dave Benham, with assistance from DosTips user Aacini
::: to get xnn to work properly with extended ASCII byte codes. Also assistance
::: from DosTips user penpen diagnosing issues reading NULL bytes, along with a
::: workaround. REPL.BAT was originally posted at:
::: http://www.dostips.com/forum/viewtopic.php?f=3&t=3855
:::

::************ Batch portion ***********
@echo off
if .%2 equ . (
  if "%~1" equ "/?" (
    <"%~f0" cscript //E:JScript //nologo "%~f0" "^:::" "" a
    exit /b 0
  ) else if /i "%~1" equ "/?regex" (
    explorer "http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx"
    exit /b 0
  ) else if /i "%~1" equ "/?replace" (
    explorer "http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx"
    exit /b 0
  ) else if /i "%~1" equ "/V" (
    <"%~f0" cscript //E:JScript //nologo "%~f0" "^::(REPL.BAT version)" "$1" a
    exit /b 0
  ) else (
    call :err "Insufficient arguments"
    exit /b 2
  )
)
echo(%~3|findstr /i "[^SMILEBVXAJ]" >nul && (
  call :err "Invalid option(s)"
  exit /b 2
)
echo(%~3|findstr /i "M"|findstr /i "A"|findstr /vi "S" >nul && (
  call :err "Incompatible options"
  exit /b 2
)
cscript //E:JScript //nologo "%~f0" %*
exit /b %errorlevel%

:err
>&2 echo ERROR: %~1. Use REPL /? to get help.
exit /b

************* JScript portion **********/
var rtn=1;
try {
  var env=WScript.CreateObject("WScript.Shell").Environment("Process");
  var args=WScript.Arguments;
  var search=args.Item(0);
  var replace=args.Item(1);
  var options="g";
  if (args.length>2) options+=args.Item(2).toLowerCase();
  var multi=(options.indexOf("m")>=0);
  var alterations=(options.indexOf("a")>=0);
  if (alterations) options=options.replace(/a/g,"");
  var srcVar=(options.indexOf("s")>=0);
  if (srcVar) options=options.replace(/s/g,"");
  var jexpr=(options.indexOf("j")>=0);
  if (jexpr) options=options.replace(/j/g,"");
  if (options.indexOf("v")>=0) {
    options=options.replace(/v/g,"");
    search=env(search);
    replace=env(replace);
  }
  if (options.indexOf("x")>=0) {
    options=options.replace(/x/g,"");
    if (!jexpr) {
      replace=replace.replace(/\\/g,"\B");
      replace=replace.replace(/\q/g,""");
      replace=replace.replace(/\x80/g,"\u20AC");
      replace=replace.replace(/\x82/g,"\u201A");
      replace=replace.replace(/\x83/g,"\u0192");
      replace=replace.replace(/\x84/g,"\u201E");
      replace=replace.replace(/\x85/g,"\u2026");
      replace=replace.replace(/\x86/g,"\u2020");
      replace=replace.replace(/\x87/g,"\u2021");
      replace=replace.replace(/\x88/g,"\u02C6");
      replace=replace.replace(/\x89/g,"\u2030");
      replace=replace.replace(/\x8[aA]/g,"\u0160");
      replace=replace.replace(/\x8[bB]/g,"\u2039");
      replace=replace.replace(/\x8[cC]/g,"\u0152");
      replace=replace.replace(/\x8[eE]/g,"\u017D");
      replace=replace.replace(/\x91/g,"\u2018");
      replace=replace.replace(/\x92/g,"\u2019");
      replace=replace.replace(/\x93/g,"\u201C");
      replace=replace.replace(/\x94/g,"\u201D");
      replace=replace.replace(/\x95/g,"\u2022");
      replace=replace.replace(/\x96/g,"\u2013");
      replace=replace.replace(/\x97/g,"\u2014");
      replace=replace.replace(/\x98/g,"\u02DC");
      replace=replace.replace(/\x99/g,"\u2122");
      replace=replace.replace(/\x9[aA]/g,"\u0161");
      replace=replace.replace(/\x9[bB]/g,"\u203A");
      replace=replace.replace(/\x9[cC]/g,"\u0153");
      replace=replace.replace(/\x9[dD]/g,"\u009D");
      replace=replace.replace(/\x9[eE]/g,"\u017E");
      replace=replace.replace(/\x9[fF]/g,"\u0178");
      replace=replace.replace(/\b/g,"b");
      replace=replace.replace(/\f/g,"f");
      replace=replace.replace(/\n/g,"n");
      replace=replace.replace(/\r/g,"r");
      replace=replace.replace(/\t/g,"t");
      replace=replace.replace(/\v/g,"v");
      replace=replace.replace(/\x[0-9a-fA-F]{2}|\u[0-9a-fA-F]{4}/g,
        function($0,$1,$2){
          return String.fromCharCode(parseInt("0x"+$0.substring(2)));
        }
      );
      replace=replace.replace(/\B/g,"\");
    }
    search=search.replace(/\\/g,"\B");
    search=search.replace(/\q/g,""");
    search=search.replace(/\x80/g,"\u20AC");
    search=search.replace(/\x82/g,"\u201A");
    search=search.replace(/\x83/g,"\u0192");
    search=search.replace(/\x84/g,"\u201E");
    search=search.replace(/\x85/g,"\u2026");
    search=search.replace(/\x86/g,"\u2020");
    search=search.replace(/\x87/g,"\u2021");
    search=search.replace(/\x88/g,"\u02C6");
    search=search.replace(/\x89/g,"\u2030");
    search=search.replace(/\x8[aA]/g,"\u0160");
    search=search.replace(/\x8[bB]/g,"\u2039");
    search=search.replace(/\x8[cC]/g,"\u0152");
    search=search.replace(/\x8[eE]/g,"\u017D");
    search=search.replace(/\x91/g,"\u2018");
    search=search.replace(/\x92/g,"\u2019");
    search=search.replace(/\x93/g,"\u201C");
    search=search.replace(/\x94/g,"\u201D");
    search=search.replace(/\x95/g,"\u2022");
    search=search.replace(/\x96/g,"\u2013");
    search=search.replace(/\x97/g,"\u2014");
    search=search.replace(/\x98/g,"\u02DC");
    search=search.replace(/\x99/g,"\u2122");
    search=search.replace(/\x9[aA]/g,"\u0161");
    search=search.replace(/\x9[bB]/g,"\u203A");
    search=search.replace(/\x9[cC]/g,"\u0153");
    search=search.replace(/\x9[dD]/g,"\u009D");
    search=search.replace(/\x9[eE]/g,"\u017E");
    search=search.replace(/\x9[fF]/g,"\u0178");
    if (options.indexOf("l")>=0) {
      search=search.replace(/\b/g,"b");
      search=search.replace(/\f/g,"f");
      search=search.replace(/\n/g,"n");
      search=search.replace(/\r/g,"r");
      search=search.replace(/\t/g,"t");
      search=search.replace(/\v/g,"v");
      search=search.replace(/\x[0-9a-fA-F]{2}|\u[0-9a-fA-F]{4}/g,
        function($0,$1,$2){
          return String.fromCharCode(parseInt("0x"+$0.substring(2)));
        }
      );
      search=search.replace(/\B/g,"\");
    } else search=search.replace(/\B/g,"\\");
  }
  if (options.indexOf("l")>=0) {
    options=options.replace(/l/g,"");
    search=search.replace(/([.^$*+?()[{\|])/g,"\$1");
    if (!jexpr) replace=replace.replace(/$/g,"$$$$");
  }
  if (options.indexOf("b")>=0) {
    options=options.replace(/b/g,"");
    search="^"+search
  }
  if (options.indexOf("e")>=0) {
    options=options.replace(/e/g,"");
    search=search+"$"
  }
  var search=new RegExp(search,options);
  var str1, str2;

  if (srcVar) {
    str1=env(args.Item(3));
    str2=str1.replace(search,jexpr?replFunc:replace);
    if (!alterations || str1!=str2) if (multi) {
      WScript.Stdout.Write(str2);
    } else {
      WScript.Stdout.WriteLine(str2);
    }
    if (str1!=str2) rtn=0;
  } else if (multi){
    var buf=1024;
    str1="";
    while (!WScript.StdIn.AtEndOfStream) {
      str1+=WScript.StdIn.Read(buf);
      buf*=2
    }
    str2=str1.replace(search,jexpr?replFunc:replace);
    WScript.Stdout.Write(str2);
    if (str1!=str2) rtn=0;
  } else {
    while (!WScript.StdIn.AtEndOfStream) {
      str1=WScript.StdIn.ReadLine();
      str2=str1.replace(search,jexpr?replFunc:replace);
      if (!alterations || str1!=str2) WScript.Stdout.WriteLine(str2);
      if (str1!=str2) rtn=0;
    }
  }
} catch(e) {
  WScript.Stderr.WriteLine("JScript runtime error: "+e.message);
  rtn=3;
}
WScript.Quit(rtn);

function replFunc($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) {
  var $=arguments;
  return(eval(replace));
}

ВАЖНОЕ ОБНОВЛЕНИЕ

Я прекратил разработку REPL.BAT и заменил его на JREPL.BAT. Эта новая утилита имеет все те же функциональные возможности REPL.BAT и многое другое:

  • Поддержка Unicode UTF-16LE через собственные возможности Unicode CSCRIPT и любой другой набор символов (включая UTF-8) через ADO.
  • Прочтите прямо из /write непосредственно в файл: нет необходимости в каналах, перенаправлении или переместить команду.
  • Включить предоставленный пользователем JScript
  • Функция перевода похожа на unix tr, только она также поддерживает поиск в регулярном выражении и замену JScript
  • Отменить несогласованный текст
  • Строки вывода префикса с номером строки
  • и более…

Как всегда, полная документация встроена в скрипт.

Теперь исходное тривиальное решение еще проще:

jrepl "foo" "bar" /f test.txt /o -

Текущая версия JREPL.BAT доступна в DosTips. Прочитайте все последующие сообщения в потоке, чтобы увидеть примеры использования и историю разработки.

Ответ 8

Использовать FNR

Используйте утилиту fnr. Он получил некоторые преимущества перед fart:

  • Регулярные выражения
  • Дополнительный графический интерфейс. Имеет кнопку «Создать командную строку» для создания текста командной строки для помещения в командный файл.
  • Многострочные шаблоны: GUI позволяет вам легко работать с многострочными шаблонами. В FART вы должны вручную избегать разрывов строк.
  • Позволяет выбрать кодировку текстового файла. Также есть опция автоматического определения.

Скачать FNR можно здесь: http://findandreplace.io/?z=codeplex

Пример использования: fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"

Ответ 9

Я не думаю, что есть способ сделать это с помощью любых встроенных команд. Я предлагаю вам скачать что-то вроде Gnuwin32 или UnxUtils и используйте команду sed (или загрузите только sed):

sed -c s/FOO/BAR/g filename

Ответ 10

Я знаю, что опаздываю на вечеринку.

Лично мне нравится решение по адресу:
 — http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

Мы также широко используем функцию Dedupe, чтобы ежедневно доставлять примерно 500 электронных писем через SMTP:
— https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o

и они оба работают изначально без каких-либо дополнительных инструментов или утилит.

ЗАМЕНИТЕЛЬ:

DEL New.txt
setLocal EnableDelayedExpansion
For /f "tokens=* delims= " %%a in (OLD.txt) do (
Set str=%%a
set str=!str:FOO=BAR!
echo !str!>>New.txt
)
ENDLOCAL

DEDUPLICATOR (обратите внимание на использование -9 для номера ABA):

REM DE-DUPLICATE THE Mapping.txt FILE
REM THE DE-DUPLICATED FILE IS STORED AS new.txt

set MapFile=Mapping.txt
set ReplaceFile=New.txt

del %ReplaceFile%
::DelDupeText.bat
rem https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o
setLocal EnableDelayedExpansion
for /f "tokens=1,2 delims=," %%a in (%MapFile%) do (
set str=%%a
rem Ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString
set str=!str:~-9!
set str2=%%a
set str3=%%a,%%b

find /i ^"!str!^" %MapFile%
find /i ^"!str!^" %ReplaceFile%
if errorlevel 1 echo !str3!>>%ReplaceFile%
)
ENDLOCAL

Спасибо!

Ответ 11

Когда вы работаете с Git в Windows, просто запустите git-bash
и используйте sed. Или, используя Windows 10, запустите «Bash в Ubuntu в Windows» (из подсистемы Linux) и используйте sed.

Редактор потока, но может редактировать файлы напрямую, используя следующую команду:

sed -i -e 's/foo/bar/g' filename
  • -i используется для редактирования на месте с именем файла.
  • -e указывает команду для запуска.
    • s используется для замены найденного выражения «foo» на «bar», а g используется для замены найденных совпадений.

Примечание ereOn:

Если вы хотите заменить строку в файлах с версией только в репозитории Git, вы можете использовать:

git ls-files <eventual subfolders & filters> | xargs sed -i -e 's/foo/bar/g'

который творит чудеса.

Ответ 12

Я использовал perl, и это работает чудесно.

perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" <fileName>

.orig — это расширение, которое оно добавит к исходному файлу

Для нескольких файлов, соответствующих *.html

for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x

Ответ 13

Я играл с некоторыми из существующих ответов здесь и предпочитаю мое улучшенное решение…

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace "foo", "bar" }"

или если вы хотите сохранить вывод снова в файл…

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace "foo", "bar" }" > outputFile.txt

Преимущество этого в том, что вы можете транслировать вывод из любой программы. Посмотрите также на использование регулярных выражений. Не удалось решить, как сделать его в BAT файл для более легкого использования, хотя…: (

Ответ 14

С replacer.bat

1) С опцией e?, которая будет оценивать специальные последовательности символов, такие как nr и последовательности Unicode. В этом случае будут заменены кавычки "Foo" и "Bar":

call replacer.bat "e?C:content.txt" "u0022Foou0022" "u0022Baru0022"

2) Прямая замена, где Foo и Bar не указаны.

call replacer.bat "C:content.txt" "Foo" "Bar"

Ответ 15

Здесь решение, которое я нашел, работало на Win XP. В моем запущенном пакетном файле я включил следующее:

set value=new_value

:: Setup initial configuration
:: I use && as the delimiter in the file because it should not exist, thereby giving me the whole line
::
echo --> Setting configuration and properties.
for /f "tokens=* delims=&&" %%a in (configconfig.txt) do ( 
  call replace.bat "%%a" _KEY_ %value% configtemp.txt 
)
del configconfig.txt
rename configtemp.txt config.txt

Файл replace.bat выглядит следующим образом. Я не нашел способ включить эту функцию в один и тот же командный файл, потому что переменная %%a всегда, кажется, дает последнее значение в цикле for.

replace.bat:

@echo off

:: This ensures the parameters are resolved prior to the internal variable
::
SetLocal EnableDelayedExpansion

:: Replaces Key Variables
::
:: Parameters:
:: %1  = Line to search for replacement
:: %2  = Key to replace
:: %3  = Value to replace key with
:: %4  = File in which to write the replacement
::

:: Read in line without the surrounding double quotes (use ~)
::
set line=%~1

:: Write line to specified file, replacing key (%2) with value (%3)
::
echo !line:%2=%3! >> %4

:: Restore delayed expansion
::
EndLocal

Ответ 16

Взгляните на Есть ли какая-либо утилита sed для cmd.exe, которая запрашивала эквивалент sed под Windows, также должна применяться к этому вопросу. Краткое содержание:

  • Это можно сделать в пакетном файле, но это не очень.
  • Множество доступных сторонних исполняемых файлов, которые сделают это для вас, если у вас есть роскошь установки или просто копирования через exe
  • Может быть сделано с VBScript или аналогичным, если вам нужно что-то, что можно запустить в окне Windows без изменений и т.д.

Ответ 17

Может быть, немного поздно, но я часто ищу похожие вещи, так как я не хочу испытывать боль при получении одобренного программного обеспечения.

Однако вы обычно используете оператор FOR в разных формах. Кто-то создал полезный командный файл, который выполняет поиск и замену. Посмотрите здесь. Важно понимать ограничения предоставленного пакетного файла. По этой причине я не копирую исходный код в этом ответе.

Ответ 18

Два пакетных файла, которые предоставляют функции search and replace, были написаны членами Qaru dbenham и aacini с использованием native built-in jscript Windows native built-in jscript.

Они оба robust и very swift with large files по сравнению с обычными пакетными сценариями, а также simpler в использовании для базовой замены текста. Они оба имеют соответствие шаблону Windows regular expression.

  1. Этот sed-like вспомогательный пакетный файл называется repl.bat (от dbenham).

    Пример использования литерала L:

    echo This is FOO here|repl "FOO" "BAR" L
    echo and with a file:
    type "file.txt" |repl "FOO" "BAR" L >"newfile.txt"
    
  2. Этот grep-like вспомогательный командный файл называется findrepl.bat (от aacini).

    Пример с активными регулярными выражениями:

    echo This is FOO here|findrepl "FOO" "BAR" 
    echo and with a file:
    type "file.txt" |findrepl "FOO" "BAR" >"newfile.txt"
    

Обе они становятся мощными общесистемными утилитами, when placed in a folder that is on the path, или могут использоваться в той же папке с командным файлом, или из командной строки cmd.

Оба имеют переключатели без case-insensitive и многие другие функции.

Ответ 19

Команда командной оболочки работает как шарм

(
test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
)

Ответ 20

Просто столкнулся с аналогичной проблемой — «Искать и заменять текст в файлах», но, за исключением того, что для обоих имен файлов и поиска /repalce мне нужно использовать регулярное выражение. Поскольку я не знаком с Powershell и хочу сохранить мои поиски для последующего использования, мне нужно что-то более «удобное для пользователя» (желательно, если у него есть GUI).

Итак, в то время как Googling:) я нашел отличный инструмент — FAR (Найти и заменить) (а не FART).

Эта небольшая программа имеет приятный графический интерфейс и поддерживает регулярное выражение для поиска в именах файлов и внутри файлов. Только disadventage заключается в том, что если вы хотите сохранить свои настройки, вы должны запустить программу в качестве администратора (по крайней мере, на Win7).

Ответ 21

Это одно дело, что пакетный скриптинг просто не работает.

Связанный с script morechilli будет работать для некоторых файлов, но, к сожалению, он захлестнет те, которые содержат такие символы, как трубы и амперсанды.

VBScript — лучший встроенный инструмент для этой задачи. См. Эту статью для примера:
http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx

Ответ 22

Для простой замены строк в файлах я использую с тех пор свободные Xchang32.exe из Коллекция Clay Utilities for Win32.

У него есть несколько вариантов быстрой замены строк в текстовых файлах, а также байтов в двоичных файлах. Он поддерживает также подстановочные знаки в строке имени файла и может быть выполнен по этой причине также для всех файлов в каталоге, соответствующем шаблону подстановочного знака.

И ничто другое не требуется для этого небольшого 32-битного консольного приложения, чем файл Xchang32.exe, извлеченный из ZIP файла, в любую директорию, такую ​​как каталог пакетного файла, вызывающий его для замены (s).

Пример:

Xchang32.exe MyBinaryFile.bin "^x03" "^x02^x05"

Эта командная строка заменяет в файле MyBinaryFile.bin каждый байт значением 3 на два байта со значениями 2 и 5.

Общей проблемой с использованием wmic является то, что выход является файлом Unicode, хотя все символы определенно находятся в диапазоне символов ASCII, т.е. имеют значение кодовой точки ниже десятичного числа 128.

Этот небольшой пакетный код с использованием Xchang32 преобразует выходной файл wmic Unicode, содержащий только символы ASCII в текстовый файл ASCII.

@echo off
rem Remove UTF-16 little endian byte order mark.
Xchang32.exe WmicOutput.txt "^xFF^xFE" "" >nul
rem Was UTF-16 LE BOM really present in file, remove all null bytes.
if not errorlevel 1 Xchang32.exe WmicOutput.txt "^x00" "" >nul

Но иногда вывод wmic перенаправляется непосредственно в текстовый файл ASCII, в результате чего CR CR LF (0D 0D 0A) в текстовом файле ASCII вместо 0D 0A (возврат каретки + строка-строка). Эти неправильные окончания строк также можно легко скорректировать с помощью Xchang32:

Xchang32.exe WmicOutput.txt "^x0D^x0D" "^x0D"

Или все *. CSV файлы в каталоге используют символ горизонтальной вкладки в качестве разделителя, и все эти вкладки в файлах CSV должны быть заменены запятой.

Xchang32.exe *.csv "^x09" ",,"

Примечание: ^ и , имеют особое значение в синтаксисе Xchang32 и поэтому должны быть экранированы с помощью другого ^ или ,, как это сделано в командной строке выше, или переключателя /s используется для простых строк. Это описано в файле ReadMe32.txt, а также в выводе справки при запуске Xchang32.exe /? в окне командной строки.

Ответ 23

@Rachel дал отличный ответ, но вот его вариант, чтобы прочитать содержимое переменной powershell $data. Затем вы можете легко манипулировать контентом несколько раз перед записью в выходной файл. Также посмотрите, как многострочные значения задаются в пакетных файлах .bat.

@REM ASCII=7bit ascii(no bom), UTF8=with bom marker
set cmd=^
  $old = '$Param1$'; ^
  $new = 'Value1'; ^
  [string[]]$data = Get-Content 'datafile.txt'; ^
  $data = $data -replace $old, $new; ^
  out-file -InputObject $data -encoding UTF8 -filepath 'datafile.txt';
powershell -NoLogo -Noninteractive -InputFormat none -Command "%cmd%"

Ответ 24

Использовать powershell в .bat — для Windows 7 +

кодировка utf8 является необязательной, подходит для веб-сайтов

@echo off
set ffile='myfile.txt'
set fold='FOO'
set fnew='BAR'
powershell -Command "(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8"

Ответ 25

Я предпочитаю использовать sed из утилит GNU для Win32, необходимо отметить следующее

  • одинарная кавычка '' не будет работать в Windows, вместо этого используйте ""
  • sed -i не будет работать в Windows, для этого потребуется обмен файлами

Таким образом, рабочий код sed для поиска и замены текста в файле в Windows, как показано ниже

sed -e "s/foo/bar/g" test.txt > tmp.txt && mv tmp.txt test.txt

Ответ 26

Загрузите Cygwin (бесплатно) и используйте unix-подобные команды в командной строке Windows.

Ваш лучший выбор: sed

Ответ 27

Также можно увидеть инструменты Replace и ReplaceFilter в https://zoomicon.github.io/tranXform/ (источник включен). Второй — это фильтр.

Инструмент, который заменяет строки в файлах, находится в VBScript (требуется Windows Script Host [WSH] для запуска в старых версиях Windows)

Фильтр, вероятно, не работает с Unicode, если вы не перекомпилируете последний Delphi (или с FreePascal/Lazarus)

Ответ 28

Я столкнулся с этой проблемой несколько раз при кодировании в Visual С++.
Если у вас есть это, вы можете использовать Visual Studio Find and Replace Utility. Он позволяет вам выбрать папку и заменить содержимое любого файла в этой папке любым другим желаемым текстом.

В Visual Studio:
Изменить → Найти и заменить
В открывшемся диалоговом окне выберите свою папку и заполните поля «Найти что» и «Заменить с».
Надеюсь, это будет полезно.

  • Remove From My Forums
  • Question

  • I am writing a batch script to replace » «, with » «. The below code works but it prefixes each line with the line number and :.

    It is the last part of the line that I am trying to replace.

    E.g.

    "                    ","BALANCE_SHEET       ","ASSETS              ","03","LEVEL_2   ",Asset Accounts,"                              ",

    To be replaced as

    "                    ","BALANCE_SHEET       ","ASSETS              ","03","LEVEL_2   ",Asset Accounts,"                              "

    Code:

    @echo off &setlocal
    set "search="                              ","
    set "replace="                              ""
    set "textfile=Build_Accounts_Plan_Source.txt"
    set "newfile=Build_Accounts_Plan_Source_new.txt"
    
    (for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:%search%=%replace%!"
        echo(!line!
        endlocal
    ))>"%newfile%"
    type "%newfile%"

    Output:

    3:"                    ","BALANCE_SHEET       ","ASSETS              ","03","LEVEL_2   ",Asset Accounts,"                              "

    Regards,

    Ragav.

Answers

  • Did you retype the code or did you use copy/paste? Retyping is not a good idea.

    You can do this to find the cause of the problem:

    1. Run the modified code below.
    2. Use notepad.exe to open the file TempVBS.vbs in your %temp% folder.
    3. Mark & copy the code, then paste it into your reply.

    @echo off
    set «textfile=Build_Accounts_Plan_Source.txt»
    set «newfile=Build_Accounts_Plan_Source_new.txt»
    set Scr=»%temp%TempVBS.vbs»
    (  echo Set oFSO = CreateObject(«Scripting.FileSystemObject»^)
       echo Set oInput = oFSO.OpenTextFile(WScript.Arguments(0^), 1^)
       echo sData = Replace(oInput.ReadAll, «,» ^& VbCrLf, VbCrLf^)
       echo Set oOutput = oFSO.CreateTextFile(WScript.Arguments(1^), True^)
       echo oOutput.Write sData
       echo oInput.Close
       echo oOutput.Close) > %Scr%
    cscript //nologo %Scr% %textfile% %newfile%

    • Marked as answer by

      Wednesday, February 12, 2014 12:37 AM

  • Files that start with

    @echo off

    are BATCH files, not VBScript files! You must save the code with a .bat extension.

    • Marked as answer by
      Ragavhere
      Wednesday, February 12, 2014 12:37 AM

What do you do if you have to replace a single word in dozens, or even hundreds or thousands, of text files? You keep calm and download Notepad++ [Broken URL Removed] or Replace Text [No Longer Available]. These two utilities will do the job in seconds.

It’s a dilemma common among developers and programmers. Imagine you’re managing a project with hundreds or thousands of files. When a product name that appears on almost every page changes, you can hardly go through each page to manually search and change the name. No, you’re smarter than that.

You fire up Google, you find this article, and you learn about a solution that only takes seconds.

How to Edit Multiple Files in Bulk

You can either use Notepad++ or a dedicated tool called Replace Text to bulk-edit your files.

Notepad++

First, allow Notepad++ to find the word in all the files you need to edit. Open Notepad++ and go to Search > Find in Files… or press CTRL+SHIFT+F. This opes the Find in Files menu.

Under Find what:, enter the word or phrase that you need to change. Under Replace with:, enter the new word or phrase. Finally, set the Directory: where the affected files are located, so that Notepad++ knows where to search.

You can also use advanced settings, which I’ve outlined further down. When all is set, click Find All if you need to double-check the hits or Replace in Files if you want Notepad++ to immediately apply the changes. Depending on the number of files Notepad++ is searching, this can take a few seconds.

If you went with Find All, you’ll get a list of hits. Remove all the files you don’t want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all.

Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you’ll find an option to Replace All in All Opened Documents.

Again, you can make several advanced settings, as explained below.

Advanced Search and Replace Settings in Notepad++

Under Find in Files, you can add Filters to search only in certain file types. For example, add *.doc to search only in DOC files. Likewise, you can search for files with a certain name, regardless of file type. Add *.* to search any file name and type.

When you choose a directory with sub-folders, check In all sub-folders and In hidden folders to search those, too. You might also want to check Match whole word only, so you don’t accidentally edit a partial match.

The Search Mode in both the Find in Files and Replace menus allows you to make advanced searches and replacements. Select Extended if you are using extensions, for example to replace a character with a new line (n). Select Regular expression if you’re using operators to find and replace all matching words or phrases. You can stick with Normal if you’re just replacing text with text.

Replace Text [No Longer Available]

With Replace Text, you can set up a Replace Group to add multiple files and/or directories and multiple replacements.

To start, create a new group. Go to Replace > Add Group, and give your group a name.

Right-click your group and select Add File(s)… to add the files and/or folders you want to edit. In the Files / Folder Properties, select your Source Type, i.e., a single file or folder, then choose the Source File / Folder Path. If you choose to add a folder, you can also include and exclude file types by adding them to the Include File Filter or Exclude File Filter rows. Click OK when you’re done.

To add multiple files or folders, repeat the above step.

Replace Text’s best feature is that you can choose a destination that’s different from the original location. In the File / Folder Properties, switch to the Destination tab and choose your desired Destination File / Folder Path.

Now that you’ve set up your group, it’s time to define your replacements. Select your group and go to Replace > Search/Replace Grid > Advanced Edit… Now you can add the Search Text and Replace Text. Be sure to look in the drop-down menu at the bottom to customize the search and replace options.

Like with Notepad++, you can use advanced search strings and operators. Unlike Notepad++, you can add as many search and replace instances as you like and Replace Text will run through all of them when you run the process.

To make the replacements, go to Replace > Start Replacing or press CTRL+R.

What Is Notepad++?

Notepad++ is a free source code editor and Windows Notepad alternative. It’s released under a GNU General Public License, making it an open-source tool.

Furthermore, Notepad++ is a lightweight application that conserves resources, which makes it good for the environment:

By optimizing as many routines as possible without losing user friendliness, Notepad++ is trying to reduce the world carbon dioxide emissions. When using less CPU power, the PC can throttle down and reduce power consumption, resulting in a greener environment.

Here’s a small selection of Notepad++ features that make this the perfect tool for writing and editing (code):

  • Numbered lines for easier navigation.

  • Automatic and customizable highlighting and folding of coding syntax.

  • Support for Perl Compatible Regular Expression (PCRE) search-and-replace.

  • Auto-completion that includes word completion, function completion, and function parameters hint.

  • A tabbed interface that lets you work with multiple documents in parallel.

  • Editing of multiple lines at once, using either CTRL+mouse-selection or column editing.

What Is Replace Text?

Replace Text is a whole lot simpler than Notepad++. It does one job: replacing text. Ecobyte, the company behind Replace Text, is mindful of its impact. Hence, the software with a cause comes with an unusual EULA:

Unfortunately, Replace Text is no longer supported and no help file is available in Windows 10. I have covered it anyhow because it offers more advanced features than Notepad++ for this particular application.

Search and Replace Made Easy

One of the two utilities above should do the job for you. If you only have a simple search-and-replace job or if the additional features of Notepad++ sound useful, you should give it a try. If you need to edit not only multiple files, but also need to make multiple different replacements, it’s worth looking into Replace Text.

Which one did you choose and did it work as prescribed? Have you found other tools that can search-and-replace text? Let us know in the comments below!

Image Credit: Fabrik Bilder via Shutterstock.com

Понравилась статья? Поделить с друзьями:
  • Windows error reporting 1001 имя события bluescreen
  • Windows error repair tool windows 7
  • Windows final или insider что это
  • Windows error recovery что это значит
  • Windows filtering platform filter has been changed