Replace text in all files windows

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.

If you can install third-party utilities, Gnu sed is tailor-made for this type of operation. The link points to a Windows version hosted at Sourceforge that you can download and install. This would be the syntax at the prompt:

for %i in (*.txt) do sed -i "s/1 setlinewidth/10 setlinewidth/g" %i

Note: with the -i option, sed is going to overwrite the files in question, so make sure you have easily available backups just in case something goes wrong.

If you can’t install the sed utility, this is going to be much more difficult using just the built-in batch language.

Edit: I put together a small batch file that will perform the replacement without any external tools. Save it as foo.cmd or whatever your preferred name is and invoke it from the command line as: foo.cmd

A caveat: This is written very specifically from the examples in your question. If there is other text or even extra spaces at the beginning or end of the line before/after 1 setlinewidth, this batch file will not work. This will also save a copy of the original text file as with a .bak extension (e.g. textfile.txt.bak).

@echo off
setlocal ENABLEEXTENSIONS
setlocal ENABLEDELAYEDEXPANSION

for %%a in (*.txt) do (
    echo Processing %%a...
    for /f "delims=^ tokens=1" %%i in (%%a) do (
        if /i "%%i"=="1 setlinewidth" (
            echo 10 setlinewidth>>%%a.new
        ) else (
            echo %%i>>%%a.new
        )
    )
    move /y %%a %%a.bak > nul
    ren %%a.new %%a
)

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

Найти и заменить текст в нескольких файлах

Сначала загрузите инструмент поиска и замены и откройте его. Поскольку это портативное программное обеспечение, вам не нужно его устанавливать. После открытия инструмента поиска и замены появится следующий экран:

Найти и заменить текст в нескольких файлах

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

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

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

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

Если вы хотите добавить несколько расширений, добавьте их следующим образом:

* .css, *. php, *. txt

С другой стороны, если вы хотите включить все файлы, кроме .exe и подобных. Чтобы исключить конкретное расширение, просто введите следующее в разделе «Исключить маску»:

*.исполняемый

Или,

* .exe, * .dll

После этого нужно ввести текст в поле «Найти». Вы можете ввести одно слово или строку.

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

Добавить слова для замены

Теперь у вас есть два варианта. Во-первых, вы можете нажать кнопку «Заменить», чтобы немедленно заменить этот текст. Во-вторых, вы можете получить команду, которую нужно использовать через командную строку, чтобы получить то же самое. Вы получите команду в поле «Использование команды», и она будет выглядеть следующим образом:

«C: Users Sudip Downloads Programs fnr.exe» —cl —dir «C: Users Sudip Desktop genesis» —fileMask «* .php, *. Css» —excludeFileMask » * .dll, * .exe «—includeSubDirectories —find» genesis «- заменить» sudip «

Здесь, C: Users Sudip Downloads Programs fnr.exe это каталог инструмента поиска и замены и C: Users Sudip Desktop genesis это каталог, в котором размещены все мои файлы.

* .php, *. css — это включенные расширения файлов.

* .dll, * .exe — исключенные расширения файлов.

Я искал генезис и заменил его на sudip.
Получить команду для замены текста

Просто скопируйте команду и вставьте ее в командную строку. После выполнения команды вы получите сообщение, подобное этому:

Найти и заменить текст с помощью командной строки

Вот и все!

Если вам это нравится, вы можете скачать его с здесь.

Найти и заменить текст с помощью командной строки .

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

Что вы делаете, если вам нужно заменить одно слово в десятках или даже сотнях или тысячах текстовых файлов? Вы сохраняете спокойствие и загружаете Notepad ++ или Replace Text [Больше не доступно]. Эти две утилиты сделают работу за считанные секунды.

Эта дилемма распространена среди разработчиков и программистов. Представьте, что вы управляете проектом с сотнями или тысячами файлов. Когда имя продукта, которое появляется почти на каждой странице, изменяется, вы вряд ли сможете просмотреть каждую страницу, чтобы выполнить поиск и изменить название вручную. Нет, ты умнее этого.

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

Как редактировать несколько файлов навалом

Вы можете использовать Notepad ++ или специальный инструмент под названием «Заменить текст» для массового редактирования. ваших файлов.

Notepad ++

Во-первых, позвольте Notepad ++ найти слово во всех файлах, которые нужно отредактировать. Откройте Блокнот ++ и перейдите в « Поиск»> «Найти в файлах» … или нажмите сочетание клавиш CTRL + SHIFT + F. Это открывает меню «Найти в файлах».

В поле « Найти что» введите слово или фразу, которые нужно изменить. В разделе « Заменить на:» введите новое слово или фразу. Наконец, установите каталог: где находятся уязвимые файлы, чтобы Notepad ++ знал, где искать.

Как найти и заменить слова в нескольких файлах Блокнот Найти в файлах

Вы также можете использовать расширенные настройки, которые я описал ниже. Когда все установлено, нажмите « Найти все», если вам нужно дважды проверить совпадения, или « Заменить в файлах», если вы хотите, чтобы Notepad ++ немедленно применил изменения. В зависимости от количества файлов, которые ищет Notepad ++, это может занять несколько секунд.

Если вы пошли с Find All , вы получите список хитов. Удалите все файлы, которые вы не хотите редактировать, выбрав их и нажав клавишу DEL, затем щелкните правой кнопкой мыши остальные файлы и выберите « Открыть все» .

Теперь перейдите в Search> Replace или нажмите CTRL + H , чтобы запустить меню Replace. Здесь вы найдете опцию Заменить все во всех открытых документах .

Как найти и заменить слова в нескольких файлах Замените блокнот

Опять же, вы можете сделать несколько дополнительных настроек, как описано ниже.

Расширенный поиск и замена настроек в Notepad ++

В разделе « Найти в файлах» вы можете добавить фильтры для поиска только в определенных типах файлов. Например, добавьте * .doc для поиска только в файлах DOC. Кроме того, вы можете искать файлы с определенным именем, независимо от типа файла. Добавьте *. * Для поиска любого имени файла и типа.

Когда вы выбираете каталог с подпапками, установите флажок Во всех подпапках и В скрытых папках, чтобы искать их тоже. Вы также можете установить флажок « Совпадение всего слова» , чтобы случайно не редактировать частичное совпадение.

Режим поиска в меню «Найти в файлах» и «Заменить» позволяет выполнять расширенный поиск и замену. Выберите Extended, если вы используете расширения, например, чтобы заменить символ новой строкой ( n). Выберите Регулярное выражение, если вы используете операторы для поиска и замены всех подходящих слов или фраз. Вы можете придерживаться Normal, если вы просто заменяете текст текстом.

Заменить текст [больше не доступно]

С помощью «Заменить текст» вы можете настроить группу замены, чтобы добавить несколько файлов и / или каталогов и несколько замен.

Для начала создайте новую группу. Перейдите в « Заменить»> «Добавить группу» и дайте имя своей группе

Щелкните правой кнопкой мыши свою группу и выберите « Добавить файл (ы)…», чтобы добавить файлы и / или папки, которые вы хотите редактировать. В окне «Свойства файла / папки» выберите тип источника , т. Е. Отдельный файл или папку, затем выберите « Путь к исходному файлу / папке» . Если вы решите добавить папку, вы также можете включать и исключать типы файлов, добавляя их в строки « Включить фильтр файлов» или « Исключить фильтр файлов» . Нажмите OK, когда вы закончите.

Как найти и заменить слова в нескольких файлах Свойства папки «Заменить текстовые файлы»

Чтобы добавить несколько файлов или папок, повторите описанный выше шаг.

Лучшая функция Replace Text в том, что вы можете выбрать пункт назначения, отличный от исходного местоположения. В свойствах файла / папки перейдите на вкладку « Место назначения » и выберите нужный путь к файлу / папке для пункта назначения .

Теперь, когда вы создали свою группу, пришло время определить ваши замены. Выберите свою группу и перейдите в « Заменить»> «Найти / заменить сетку»> «Расширенное редактирование»… Теперь вы можете добавить текст для поиска и « Заменить текст» . Обязательно загляните в раскрывающееся меню внизу, чтобы настроить параметры поиска и замены.

Как найти и заменить слова в нескольких файлах Заменить текст Advanced Edit

Как и в случае с Notepad ++, вы можете использовать строки расширенного поиска и операторы. В отличие от Notepad ++, вы можете добавить столько экземпляров поиска и замены, сколько захотите, и Replace Text будет проходить через все из них при запуске процесса.

Чтобы сделать замены, перейдите в « Замена»> «Начать замену» или нажмите CTRL + R.

Об инструментах

Что такое Блокнот ++?

Notepad ++ — это бесплатный редактор исходного кода и альтернатива Windows Notepad. Он выпущен на условиях GNU General Public License , что делает его открытым исходным инструмент.

Кроме того, Notepad ++ — это легковесное приложение, которое сохраняет ресурсы, что делает его полезным для окружающей среды:

Оптимизируя как можно больше процедур без потери удобства, Notepad ++ пытается сократить выбросы углекислого газа в мире. При использовании меньшей мощности процессора ПК может снизить скорость и снизить энергопотребление, что приведет к более экологичной среде.

Вот небольшой набор функций Notepad ++, которые делают его идеальным инструментом для написания и редактирования (код):

  • Пронумерованные линии для облегчения навигации.

  • Автоматическая и настраиваемая подсветка и свертывание синтаксиса кодирования.

  • Поддержка поиска и замены Perl-совместимых регулярных выражений (PCRE).

  • Автозаполнение, которое включает завершение слова, завершение функции и подсказку параметров функции.

  • Интерфейс с вкладками, который позволяет вам работать с несколькими документами параллельно.

  • Редактирование нескольких строк одновременно, используя либо CTRL + выделение мыши, либо редактирование столбцов.

Что такое заменить текст?

Заменить текст намного проще, чем Notepad ++. Это делает одну работу: замена текста. Ecobyte, компания, занимающаяся заменой текста, помнит о ее влиянии. Следовательно, программное обеспечение с указанием причины поставляется с необычным лицензионным соглашением:

Как найти и заменить слова в нескольких файлах. EULA 670x452.

К сожалению, Replace Text больше не поддерживается, и в Windows 10 отсутствует файл справки. Я все равно рассмотрел его, поскольку он предлагает более продвинутые функции, чем Notepad ++ для этого конкретного приложения.

Поиск и замена Made Easy

Одна из двух утилит выше должна сделать эту работу за вас. Если у вас есть только простое задание поиска и замены или если полезны дополнительные функции Notepad ++, попробуйте. Если вам нужно отредактировать не только несколько файлов , но также нужно сделать несколько различных замен, стоит посмотреть на Replace Text.

Какой из них вы выбрали, и он работал как предписано? Нашли ли вы другие инструменты, которые могут искать и заменять текст? Дайте нам знать в комментариях ниже!

Изображение предоставлено: Фабрик Билдер через Shutterstock.com

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.

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.

A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.

I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file:

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

To explain it:

  • powershell starts up powershell.exe, which is included in Windows 7
  • -Command "... " is a command line arg for powershell.exe containing the command to run
  • (gc myFile.txt) reads the content of myFile.txt (gc is short for the Get-Content command)
  • -replace 'foo', 'bar' simply runs the replace command to replace foo with bar
  • | Out-File myFile.txt pipes the output to the file myFile.txt
  • -encoding ASCII prevents transcribing the output file to unicode, as the comments point out

Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is C:WINDOWSsystem32WindowsPowerShellv1.0

Update
Apparently modern windows systems have PowerShell built in allowing you to access this directly using

(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt

If you are on Windows version that supports .Net 2.0, I would replace your shell. PowerShell gives you the full power of .Net from the command line. There are many commandlets built in as well. The example below will solve your question. I’m using the full names of the commands, there are shorter aliases, but this gives you something to Google for.

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

Just used FARTF ind A nd R eplace T ext» command line utility):
excellent little freeware for text replacement within a large set of files.

The setup files are on SourceForge.

Usage example:

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

will preview the replacements to do recursively in the files of this Perl distribution.

Only problem: the FART website icon isn’t exactly tasteful, refined or elegant ;)


Update 2017 (7 years later) jagb points out in the comments to the 2011 article «FARTing the Easy Way – Find And Replace Text» from Mikail Tunç


As noted by Joe Jobs in the comments (Dec. 2020), if you want to replace &A for instance, you would need to use quotes in order to make sure & is not interpreted by the shell:

fart in.txt "&A" "B" 

Понравилась статья? Поделить с друзьями:
  • Repair s11 ssd скачать торрент для windows
  • Repair disc windows 7 64 bit
  • Renga скачать бесплатно на русском торрент для windows
  • Render creation error morrowind windows 10
  • Renault clip windows 7 как установить