Windows 명령줄 환경을 사용하여 파일에서 텍스트를 어떻게 찾고 바꿀 수 있습니까?

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

문제

Windows 명령줄 환경을 사용하여 배치 파일 스크립트를 작성 중이며 파일에서 일부 텍스트가 나타날 때마다 변경하고 싶습니다(예:"FOO")를 다른 이름(예:"술집").이를 수행하는 가장 간단한 방법은 무엇입니까?내장된 기능이 있나요?

도움이 되었습니까?

해결책

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

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

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' 단순히 교체 명령을 실행하여 교체합니다. foo ~와 함께 bar
  • | 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

방금 사용함 방귀 ("에프 공업 nd 아르 자형 장소 ext" 명령줄 유틸리티):
대규모 파일 세트 내에서 텍스트를 대체할 수 있는 뛰어난 작은 프리웨어입니다.

설정 파일 SourceForge에 있습니다.

사용 예:

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

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

유일한 문제:FART 웹사이트 아이콘은 세련되지도, 세련되지도, 우아하지도 않습니다.


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

파일 바꾸기.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 이상 기본적으로 유니코드(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 유니코드 기능을 통한 유니코드 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

또한 Dedupe 기능을 광범위하게 사용하여 다음에서 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-bash 그리고 사용 sed.또는 Windows 10을 사용하는 경우 "Bash on Ubuntu on Windows"(Linux 하위 시스템에서)를 시작하고 sed.

스트림 편집기이지만 다음 명령을 사용하여 파일을 직접 편집할 수 있습니다.

sed -i -e 's/foo/bar/g' filename
  • -i 옵션은 파일 이름을 편집하는 데 사용됩니다.
  • -e 옵션은 실행할 명령을 나타냅니다.
    • s 발견된 표현식 "foo"를 "bar"로 바꾸는 데 사용됩니다. g 발견된 일치 항목을 바꾸는 데 사용됩니다.

ereOn의 참고 사항:

Git 저장소의 버전 파일에서만 문자열을 바꾸려면 다음을 사용할 수 있습니다.

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

그것은 놀라운 일입니다.

나는 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 문은 다양한 형태로 사용됩니다.누군가 검색 및 바꾸기를 수행하는 유용한 배치 파일을 만들었습니다.보세요 여기.제공된 배치 파일의 제한 사항을 이해하는 것이 중요합니다.이러한 이유로 이 답변에서는 소스 코드를 복사하지 않습니다.

제공하는 두 개의 배치 파일 search and replace 함수는 Stack Overflow 회원이 작성했습니다. dbenham 그리고 aacini 사용하여 native built-in jscript Windows에서.

그들은 둘 다 robust 그리고 very swift with large files 일반 배치 스크립팅과 비교했을 때, simpler 기본적인 텍스트 교체에 사용합니다.둘 다 가지고 있어요 Windows regular expression 패턴 매칭.

  1. 이것sed-like 도우미 배치 파일이 호출됩니다. repl.bat (dbenham 작성).

    사용 예 L 리터럴 스위치:

    echo This is FOO here|repl "FOO" "BAR" L
    echo and with a file:
    type "file.txt" |repl "FOO" "BAR" L >"newfile.txt"
    
  2. 이것 grep-like 도우미 배치 파일이 호출됩니다. findrepl.bat (아아치니 작성)

    정규식이 활성화된 예:

    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에서는).

이것은 배치 스크립팅이 잘 수행되지 않는 것 중 하나입니다.

스크립트 모레칠리 linked to는 일부 파일에서는 작동하지만 불행하게도 파이프나 앰퍼샌드와 같은 문자가 포함된 파일에서는 질식할 수 있습니다.

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 인코딩은 선택 사항이며 웹 사이트에 적합합니다.

@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 명령줄에서 유닉스 계열 명령을 사용할 수 있습니다.

최선의 방법:sed

다음 위치에서 바꾸기 및 바꾸기 필터 도구를 볼 수도 있습니다. https://zoomicon.github.io/tranXform/ (소스 포함).두 번째는 필터입니다.

파일의 문자열을 바꾸는 도구는 VBScript에 있습니다(이전 Windows 버전에서 실행하려면 Windows 스크립트 호스트[WSH]가 필요함).

최신 Delphi(또는 FreePascal/Lazarus)로 다시 컴파일하지 않으면 필터가 유니코드에서 작동하지 않을 수 있습니다.

Visual C++에서 코딩하는 동안 이 문제에 여러 번 직면했습니다.있는 경우 Visual Studio 찾기 및 바꾸기 유틸리티를 사용할 수 있습니다.폴더를 선택하고 해당 폴더에 있는 파일의 내용을 원하는 다른 텍스트로 바꿀 수 있습니다.

Visual Studio에서:편집 -> 열린 대화 상자에서 찾아서 교체하고 폴더를 선택하고 "무엇을 찾으십시오"및 "대체"상자를 작성하십시오.이것이 도움이 되기를 바랍니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top