Windows コマンドライン環境を使用して、ファイル内のテキストを検索して置換するにはどうすればよいでしょうか?

StackOverflow https://stackoverflow.com/questions/60034

質問

Windows コマンドライン環境を使用してバッチ ファイル スクリプトを作成しており、ファイル内のテキスト (例:"FOO") と別の (例:"バー")。それを行う最も簡単な方法は何ですか?組み込み関数はありますか?

役に立ちましたか?

解決

ここでの回答の多くは私を正しい方向に導くのに役立ちましたが、どれも私にとって適切なものではなかったので、私の解決策を投稿します。

私は Windows 7 を使用していますが、これには PowerShell が組み込まれています。ファイル内のテキストのすべてのインスタンスを検索/置換するために使用したスクリプトは次のとおりです。

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

それを説明すると、次のようになります。

  • powershell Windows 7に含まれるpowershell.exeを起動します。
  • -Command "... " 実行するコマンドを含むpowershell.exeのコマンドライン引数です。
  • (gc myFile.txt) の内容を読みます myFile.txt (gc の略です Get-Content 指示)
  • -replace 'foo', 'bar' replace コマンドを実行して置き換えるだけです foobar
  • | Out-File myFile.txt 出力をファイルにパイプします myFile.txt

Powershell.exe はすでに PATH ステートメントの一部になっている必要がありますが、そうでない場合は追加できます。私のマシン上のそれの場所は次のとおりです C:\WINDOWS\system32\WindowsPowerShell\v1.0

他のヒント

.Net 2.0 をサポートする Windows バージョンを使用している場合は、シェルを置き換えます。 パワーシェル コマンド ラインから .Net の全機能を利用できます。多くのコマンドレットも組み込まれています。以下の例はあなたの質問を解決します。ここではコマンドの完全名を使用していますが、もっと短いエイリアスもありますが、これは Google に調べてもらうためのものです。

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

使用したばかり おなら ("F インド nd R 置き換える T ext" コマンド ライン ユーティリティ):
大規模なファイルセット内のテキストを置換するための優れた小さなフリーウェアです。

セットアップファイル SourceForge 上にあります.

使用例:

fart.exe -p -r -c -- C:\tools\perl-5.8.9\* @@APP_DIR@@ C:\tools

この Perl ディストリビューションのファイル内で再帰的に実行される置換をプレビューします。

唯一の問題:FART Web サイトのアイコンは、決して上品ではなく、洗練されていても、エレガントでもありません ;)


2017 年の更新 (7 年後) ジャグブ 指摘している コメントで 2011年の記事へ簡単な方法でおなら – テキストの検索と置換" から ミカエル・トゥンチ

交換 - 文字列置換を使用してサブストリングを交換します。説明:部分文字列を別の文字列に置き換えるには、文字列置換機能を使用します。ここに示す例では、文字列変数 str 内のすべての「teh」のスペルミスを「the」に置き換えます。

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

スクリプト出力:

teh cat in teh hat
the cat in the hat

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

ファイル 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

この改訂されたスクリプト (replace.vbs と呼びます) を使用するには、コマンド プロンプトから次のようなコマンドを入力するだけです。

cscript replace.vbs "C:\Scripts\Text.txt" "Jim " "James "

BatchSubstitute.bat dostips.com で は、純粋なバッチ ファイルを使用した検索と置換の例です。

の組み合わせを使用します FOR, FIND そして CALL SET.

文字を含む行 "&<>]|^ 間違った扱いを受ける可能性があります。


注記 - REPL.BAT に代わる優れた JREPL.BAT へのリンクについては、この回答の最後にある更新を必ず参照してください。
JREPL.BAT 7.0以降 を介して Unicode (UTF-16LE) をネイティブにサポートします。 /UTF オプション、および UTF-8 を含む他の文字セットも ADO 経由で使用できます!!!!


REPL.BAT という小さなハイブリッド JScript/バッチ ユーティリティを作成しました。 これは、コマンド ラインまたはバッチ ファイルを使用して ASCII (または拡張 ASCII) ファイルを変更する場合に非常に便利です。純粋なネイティブ スクリプトはサードパーティの実行可能ファイルをインストールする必要がなく、XP 以降の最新の Windows バージョンで動作します。また、特に純粋なバッチ ソリューションと比較した場合、非常に高速です。

REPL.BAT は単純に stdin を読み取り、JScript 正規表現の検索と置換を実行し、結果を stdout に書き込みます。

以下は、REPL.BAT が現在のフォルダー、またはさらに良いのは PATH 内のどこかにあると仮定して、test.txt 内の foo を bar に置き換える方法の簡単な例です。

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

JScript の正規表現機能により、特に検索テキストからキャプチャされた部分文字列を参照する置換テキストの機能が非常に強力になります。

このユーティリティには、ユーティリティを非常に強力にする多くのオプションが含まれています。たとえば、 M そして X オプションによりバイナリ ファイルの変更が可能になります。の M 複数行オプションを使用すると、複数行にわたる検索が可能になります。の X 拡張置換パターン オプションは、置換テキストに任意のバイナリ値を含めることを可能にするエスケープ シーケンスを提供します。

ユーティリティ全体を純粋な 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'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));
}


重要なアップデート

REPL.BAT の開発を中止し、JREPL.BAT に置き換えました。この新しいユーティリティには、REPL.BAT と同じ機能に加えて、さらに多くの機能が含まれています。

  • ネイティブ CSCRIPT Unicode 機能による Unicode UTF-16LE サポート、および ADO によるその他の文字セット (UTF-8 を含む)。
  • ファイルから直接読み取る/ファイルに直接書き込む:パイプ、リダイレクト、または移動コマンドは必要ありません。
  • ユーザー指定の JScript を組み込む
  • unix tr と同様の変換機能ですが、正規表現検索と JScript 置換もサポートしています。
  • 一致しないテキストを破棄する
  • 出力行の先頭に行番号を付ける
  • もっと...

いつものように、完全なドキュメントがスクリプト内に埋め込まれています。

元の簡単な解決策はさらに単純になりました。

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

JREPL.BAT の現在のバージョンは DosTips で入手できます。. 。スレッド内の以降の投稿をすべて読んで、使用例と開発の歴史を確認してください。

FNRを使用する

使用 fnr ユーティリティ。それに比べていくつかの利点があります fart:

  • 正規表現
  • オプションの GUI。バッチファイルに入れるコマンドラインテキストを作成するための「コマンドライン生成ボタン」があります。
  • 複数行のパターン:GUI を使用すると、複数行のパターンを簡単に操作できます。FART では、改行を手動でエスケープする必要があります。
  • テキスト ファイルのエンコーディングを選択できます。自動検出オプションもあります。

ここから FNR をダウンロードします。 http://findandreplace.io/?z=codeplex

使用例:fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"

組み込みコマンドでそれを行う方法はないと思います。次のようなものをダウンロードすることをお勧めします グヌウィン32 または UnxUtils そして使用してください sed コマンド (またはダウンロードのみ) sed):

sed -c s/FOO/BAR/g filename

パーティーに遅刻するのは分かっています..

個人的には、次のソリューションが気に入っています。- http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

また、重複排除機能を広範囲に使用して、SMTP 経由で毎日約 500 通の電子メールを以下から配信しています。- 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 (ABA 番号には -9 が使用されていることに注意してください):

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

ありがとう!

一緒に仕事をするときは Windows 上の Git あとは単に点火するだけです git-bash そして使用します sed. 。または、Windows 10 を使用している場合は、(Linux サブシステムから) 「Bash on Ubuntu on Windows」を起動し、 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'

それは驚くべき効果を発揮します。

私は 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

ここで既存の回答のいくつかを試してみましたが、改善されたソリューションを好みます...

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 ファイルに変換する方法がわかりませんでした...:-(

とともに 代替品.bat

1) あり e? 次のような特殊文字シーケンスを評価するオプション \n\r そしてユニコードシーケンス。この場合、引用符を置き換えます "Foo" そして "Bar":

call replacer.bat "e?C:\content.txt" "\u0022Foo\u0022" "\u0022Bar\u0022"

2) 簡単に置き換えることができます。 Foo そして Bar 引用されていない。

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

これは、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 (config\config.txt) do ( 
  call replace.bat "%%a" _KEY_ %value% config\temp.txt 
)
del config\config.txt
rename config\temp.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

を見てみましょう cmd.exe用のsedのようなユーティリティはありますか Windows での sed に相当するものを求めた質問は、この質問にも当てはまるはずです。エグゼクティブサマリー:

  • バッチファイルでも実行できますが、あまりきれいではありません
  • インストールするか、exe をコピーするだけの余裕がある場合は、サードパーティ製の実行可能ファイルが多数用意されています。
  • 変更を加えずに Windows ボックス上で実行できるものが必要な場合は、VBScript などを使用して実行できます。

少し遅れているかもしれませんが、ソフトウェアの承認を得るのに苦労したくないので、似たようなものを頻繁に探しています。

ただし、通常、FOR ステートメントはさまざまな形式で使用されます。検索と置換を行う便利なバッチ ファイルを作成した人がいます。見てください ここ. 。提供されるバッチ ファイルの制限を理解することが重要です。このため、この回答のソース コードはコピーしません。

提供する 2 つのバッチ ファイル search and replace 関数はスタック オーバーフロー メンバーによって作成されています dbenham そして aacini を使用して native built-in jscript Windowsで。

両方ともです robust そして very swift with large files 単純なバッチスクリプトと比較したり、 simpler 基本的なテキストの置換に使用します。彼らは両方とも持っています Windows regular expression パターンマッチング。

  1. これsed-like ヘルパーバッチファイルが呼び出されます repl.bat (デベンハム著)。

    を使用した例 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 スイッチやその他多くの機能も備えています。

Power Shell コマンドは魅力的に機能します

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

「ファイル内のテキストの検索と置換」という同様の問題に直面しましたが、ファイル名と検索/置換の両方に正規表現を使用する必要があるという例外があります。私は Powershell に詳しくなく、後で使用できるように検索内容を保存したいため、より「ユーザーフレンドリー」なもの (GUI があれば望ましい) が必要です。

それで、グーグルしていたら:)素晴らしいツールを見つけました - FAR (検索と置換) (FARTではありません)。

この小さなプログラムには優れた GUI があり、ファイル名およびファイル内を検索するための正規表現がサポートされています。唯一の欠点は、設定を保存したい場合は (少なくとも Win7 では) 管理者としてプログラムを実行する必要があることです。

これは、バッチ スクリプトではうまく対応できない点の 1 つです。

スクリプト もっと唐辛子 「リンク先」は一部のファイルでは機能しますが、残念ながらパイプやアンパサンドなどの文字が含まれるファイルでは動作しません。

VBScript は、このタスクに適した組み込みツールです。例については、この記事を参照してください。http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx

@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%"

.bat で PowerShell を使用する - Windows 7 以降の場合

utf8 エンコーディングはオプションであり、Web サイトに適しています

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

私は使用することを好みます sed から Win32 用の GNU ユーティリティ, 、次のことに注意する必要があります

  • 一重引用符 '' Windowsでは動作しないので、使用してください "" その代わり
  • sed -i Windowsでは動作しません。ファイルが必要です スワッピング

したがって、作業コードは sed Windowsでファイル内のテキストを検索して置換するには、次のようにします

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

ダウンロード シグウィン (無料) Windows コマンド ラインで Unix のようなコマンドを使用します。

最善の策:セド

Replace ツールと ReplaceFilter ツールも次の場所で確認できます。 https://zoomicon.github.io/tranXform/ (ソースが含まれています)。2枚目はフィルターです。

ファイル内の文字列を置換するツールは VBScript にあります (古い Windows バージョンで実行するには Windows Script Host [WSH] が必要です)

最新の Delphi (または FreePascal/Lazarus) で再コンパイルしない限り、フィルタは Unicode では機能しない可能性があります。

Visual C++ でコーディングしているときに、この問題に何度か直面しました。お持ちの場合は、Visual Studio の検索と置換ユーティリティを使用できます。フォルダーを選択し、そのフォルダー内のファイルの内容を他の任意のテキストに置き換えることができます。

Visual Studio で:編集 - >開いたダイアログで検索して置き換え、フォルダーを選択し、「what」と「交換」ボックスを入力します。これがお役に立てば幸いです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top