Programming

Windows 명령 줄 환경을 사용하여 파일에서 텍스트를 찾고 바꾸는 방법은 무엇입니까?

procodes 2020. 2. 15. 23:36
반응형

Windows 명령 줄 환경을 사용하여 파일에서 텍스트를 찾고 바꾸는 방법은 무엇입니까?


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에서 사용 가능 합니다. 사용 예 및 개발 히스토리를 보려면 스레드의 모든 후속 게시물을 읽으십시오.


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"


내장 명령으로 수행 할 수있는 방법이 없다고 생각합니다. Gnuwin32 또는 UnxUtils같은 것을 다운로드 하고 sed명령 (또는 다운로드 만 sed)을 사용하는 것이 좋습니다 .

sed -c s/FOO/BAR/g filename

나는 파티에 늦었다는 것을 알고있다 ..

개인적으로 나는 해결책을 좋아한다 : -http : //www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

또한 중복 제거 기능을 광범위하게 사용하여 다음을 통해 매일 약 500 개의 이메일을 SMTP를 통해 전송할 수 있습니다.- https ://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o

이들 모두 기본적으로 추가 도구 나 유틸리티가 필요하지 않습니다.

교체 자 :

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

중복 제거기 (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 "를 시작하고를 사용하십시오 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 -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 파일로 만드는 방법을 알아낼 수 없었습니다 ... :-(


replacer.bat

1) 유니 코드 시퀀스와 e?같은 특수 문자 시퀀스를 평가하는 옵션이 \n\r있습니다. 이 경우 인용 대체합니다 "Foo""Bar":

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

2) FooBar인용되지 않은 곳에서 직접 교체하십시오 .

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를위한 유틸리티처럼 나오지도 어떤이 A가 Windows에서 해당 나오지 요청이 질문에뿐만 아니라를 적용해야합니다. 행정상 개요 :

  • 배치 파일로 수행 할 수는 있지만 예쁘지 않습니다.
  • EXE 파일을 설치하거나 복사하는 것이 고급 스러우면 사용 가능한 많은 타사 실행 파일이 있습니다.
  • 수정하지 않고 Windows 상자에서 실행할 수있는 것이 필요한 경우 VBScript 또는 이와 유사한 작업을 수행 할 수 있습니다.

약간 늦을 수도 있지만 소프트웨어 승인을받는 데 따르는 어려움을 겪고 싶지 않기 때문에 비슷한 내용을 자주 찾고 있습니다.

그러나 일반적으로 FOR 문을 다양한 형식으로 사용합니다. 누군가가 검색하고 바꾸는 유용한 배치 파일을 만들었습니다. 봐 가지고 여기를 . 제공된 배치 파일의 제한 사항을 이해하는 것이 중요합니다. 이런 이유로 나는이 답변에 소스 코드를 복사하지 않습니다.


공급 것을 두 배치 파일 search and replace의 기능은 스택 오버플로 회원들에 의해 작성되었습니다 dbenhamaacini사용하여 native built-in jscriptWindows에서.

그것들은 일반 배치 스크립팅 robustvery 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.bataacini에 의해 호출 됩니다.

    정규식이 활성화 된 예 :

    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스위치와 다른 많은 기능을 가지고 있습니다.


파워 쉘 명령은 매력처럼 작동합니다

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

"파일 내에서 텍스트 검색 및 바꾸기"와 비슷한 문제에 직면했지만 파일 이름과 검색 / 대리 모두 정규식을 사용해야한다는 점을 제외하고. Powershell에 익숙하지 않고 나중에 사용하기 위해 검색을 저장하려면보다 "사용자 친화적"(GUI가있는 경우 선호) 항목이 필요합니다.

그래서 인터넷 검색 :) 나는 훌륭한 도구를 찾았습니다 -FAR (찾기 및 바꾸기) (FART 아님).

그 작은 프로그램에는 멋진 GUI가 있으며 파일 이름과 파일 내에서 검색하기위한 정규식을 지원합니다. 유일한 단점은 설정을 저장하려면 프로그램을 관리자 (적어도 Win7에서)로 실행해야한다는 것입니다.


이것은 배치 스크립팅이 잘하지 못하는 것입니다.

morechilli에 연결된 스크립트 는 일부 파일에서 작동하지만 불행히도 파이프 및 앰퍼샌드와 같은 문자가 포함 된 스크립트 에서는 질식합니다.

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"

Cygwin (무료)을 다운로드 하고 Windows 명령 행에서 유닉스 계열 명령을 사용하십시오.

최선의 방법 : sed


내가 사용하는 것을 선호하고있어 sed에서 Win32에서 대한 GNU 유틸리티 , 다음 사항을주의해야

  • 작은 따옴표 ''는 Windows에서 작동하지 않습니다. ""대신 사용하십시오.
  • sed -iWindows에서는 작동하지 않습니다. 파일 교환 이 필요합니다.

따라서 sed창에서 파일의 텍스트를 찾아 바꾸는 작업 코드 는 다음과 같습니다.

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

https://zoomicon.github.io/tranXform/ (소스 포함) 에서 Replace and ReplaceFilter 도구를 볼 수도 있습니다 . 두 번째는 필터입니다.

파일에서 문자열을 대체하는 도구는 VBScript에 있습니다 (이전 Windows 버전에서 실행하려면 WSH (Windows Script Host)가 필요함)

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


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

Visual Studio에서 : 편집-> 찾기 및 바꾸기 열린 대화 상자에서 폴더를 선택하고 "찾기"및 "바꾸기"상자를 채우십시오. 이것이 도움이 되길 바랍니다.

참고 : https://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir



반응형