Windows 명령 줄 환경을 사용하여 파일에서 텍스트를 어떻게 찾고 바꿀 수 있습니까? : “FOO”)를 다른 텍스트 (예

Windows 명령 줄 환경을 사용하여 배치 파일 스크립트를 작성하고 있으며 파일에서 일부 텍스트 (예 : “FOO”)를 다른 텍스트 (예 : “BAR”)로 변경하려고합니다. 가장 간단한 방법은 무엇입니까? 내장 기능이 있습니까?



답변

여기에 많은 답변이 올바른 방향을 알려주는 데 도움이되었지만 나에게 적합한 것은 없었으므로 솔루션을 게시하고 있습니다.

PowerShell 7과 함께 제공되는 Windows 7이 있습니다. 다음은 파일에서 모든 텍스트 인스턴스를 찾거나 바꾸는 데 사용한 스크립트입니다.

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

그것을 설명하려면 :

  • powershell Windows 7에 포함 된 powershell.exe를 시작합니다.
  • -Command "... " 실행할 명령이 포함 된 powershell.exe의 명령 줄 arg입니다.
  • (gc myFile.txt)의 내용을 읽습니다 myFile.txt( 명령의 gc줄임말 Get-Content)
  • -replace 'foo', 'bar'간단하게 대체 할 수있는 대체 명령 실행 foo과를bar
  • | Out-File myFile.txt 출력을 파일로 파이프 myFile.txt
  • -encoding ASCII 주석이 지적한 것처럼 출력 파일을 유니 코드로 전사하는 것을 방지합니다.

Powershell.exe는 이미 PATH 문의 일부이지만 추가 할 수없는 경우 추가 할 수 있습니다. 내 컴퓨터의 위치는C:\WINDOWS\system32\WindowsPowerShell\v1.0


답변

.Net 2.0을 지원하는 Windows 버전을 사용하는 경우 쉘을 교체합니다. PowerShell 은 명령 줄에서 .Net의 모든 기능을 제공합니다. 내장 된 많은 커맨드 렛이 있습니다. 아래 예제는 질문을 해결합니다. 명령의 전체 이름을 사용하고 있지만 별칭이 짧지 만 Google에 뭔가를 제공합니다.

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


답변

그냥 사용 방귀 ( ” F 공업 차 R eplace T : 내선”명령 줄 유틸리티)
파일의 큰 세트 내의 텍스트 교체를 위해 우수한 작은 프리웨어입니다.

설정 파일 은 SourceForge에 있습니다.

사용 예 :

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

이 Perl 배포 파일에서 재귀 적으로 수행 할 대체를 미리 볼 것입니다.

유일한 문제 : FART 웹 사이트 아이콘은 맛 있거나 세련되거나 우아하지 않습니다.)


업데이트 2017 (7 년 이상) jagb 종료 지점 코멘트에 2011 년 기사 ” 쉬운 방법 방 귀 – 텍스트 찾기 및 바꾸기 “에서 Mikail Tunç


답변

바꾸기-문자열 대체를 사용하여 하위 문자열 바꾸기 설명 : 하위 문자열을 다른 문자열로 바꾸려면 문자열 대체 기능을 사용하십시오. 여기에 표시된 예제는 문자열 변수 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.batonsstips.com 은 순수한 배치 파일을 사용한 검색 및 교체의 예입니다.

그것은의 조합을 사용 FOR, FIND하고 CALL SET.

문자가 포함 된 행 "&<>]|^은 잘못 취급 될 수 있습니다.



답변

참고 -REPL.BAT를 대체하는 우수한 JREPL.BAT 링크에 대해서는이 답변의 끝에 업데이트를 참조하십시오.
JREPL.BAT 7.0 이상/UTF옵션을 통해 기본적으로 유니 코드 (UTF-16LE) 및 UTF-8을 포함하여 ADO !!!!


명령 줄이나 배치 파일을 통해 ASCII (또는 확장 ASCII) 파일을 수정하는 데 매우 편리한 REPL.BAT라는 작은 하이브리드 JScript / 배치 유틸리티를 작성했습니다 . 순수 네이티브 스크립트는 타사 실행 파일을 설치할 필요가 없으며 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 정규식 기능은 검색 텍스트에서 캡처 된 하위 문자열을 참조 할 수있는 대체 텍스트 기능을 매우 강력하게 만듭니다.

유틸리티에 많은 옵션을 포함시켜 매우 강력하게 만들었습니다. 예를 들어, MX옵션을 결합하면 이진 파일을 수정할 수 있습니다! 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 유니 코드 기능을 통한 유니 코드 UTF-16LE 지원 및 ADO를 통한 기타 문자 세트 (UTF-8 포함).
  • 파이프에서 파일을 직접 읽거나 파일에 직접 쓰거나 파이프, 리디렉션 또는 이동 명령이 필요하지 않습니다.
  • 사용자 제공 JScript 통합
  • 유닉스 tr과 비슷한 번역 기능으로 정규식 검색 및 JScript 바꾸기 만 지원합니다.
  • 일치하지 않는 텍스트 삭제
  • 라인 번호가있는 접두사 출력 라인
  • 그리고 더…

항상 그렇듯이 전체 문서가 스크립트에 포함되어 있습니다.

원래 사소한 솔루션은 이제 더 간단 해졌습니다.

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

JREPL.BAT의 현재 버전은 DosTips에서 사용 가능 합니다. 사용 예 및 개발 히스토리를 보려면 스레드의 모든 후속 게시물을 읽으십시오.