Windows 명령줄 환경을 사용하여 파일 내의 텍스트를 검색 및 대체하려면 어떻게 해야 합니까?
Windows 명령줄 환경을 사용하여 배치 파일 스크립트를 작성하고 있으며 파일 내의 일부 텍스트(예: "FOO")를 다른 텍스트(예: "BAR")로 변경하려고 합니다.그것을 하는 가장 간단한 방법은 무엇입니까?내장된 기능이 있습니까?
여기 있는 많은 답변이 올바른 방향으로 인도하는 데 도움이 되었지만, 어느 답변도 나에게 맞지 않아 솔루션을 게시합니다.
PowerShell이 내장된 Windows 7을 사용하고 있습니다.파일 내의 모든 텍스트인스턴스를 검색/바꾸기 위해 사용한 스크립트는 다음과 같습니다.
powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"
설명:
powershell는 Windows 7 에되어 있는 를 합니다.powershell.exe 는 Windows 7 에 되어 있습니다.-Command "... "는 powershell.exe를 실행하는입니다.(gc myFile.txt)을myFile.txt)gc로 '아까불까불까불까불까불까불까불까불까불까불까요?Get-Content명령어)-replace 'foo', 'bar'하여 ""를 바꿉니다.foobar| Out-File myFile.txt을 로 연결합니다.myFile.txt-encoding ASCII는, 가 지적하고을 Unicode 에 합니다.
Powershell.exe는 PATH를 사용합니다.제 기계에 있는 위치는요소는C:\WINDOWS\system32\WindowsPowerShell\v1.0
되어 있기 때문에 PowerShell을 수 있습니다.
(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
를 지원하는 Windows 버전인 경우.넷 2.0, 셸을 교체하겠습니다.PowerShell은 의 모든 기능을 제공합니다.명령줄에서 네트로 이동합니다.또한 많은 커맨드렛이 내장되어 있습니다.다음 예시는 당신의 궁금증을 해결해 줄 것입니다.명령어의 전체 이름을 사용하고 있습니다. 더 짧은 별칭도 있지만, 이것은 구글에 대한 정보를 제공합니다.
(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
방금 사용한 BANGE ("Find A nd R eplace T ext" 명령줄 유틸리티):
대용량의 파일 세트 내에서 텍스트 치환을 위한 뛰어난 프리웨어.
셋업 파일은 Source Forge에 있습니다.
사용 예:
fart.exe -p -r -c -- C:\tools\perl-5.8.9\* @@APP_DIR@@ C:\tools
는, 이 Perl 디스트리뷰션의 파일에 재귀적으로 행해지는 치환을 미리 봅니다.
유일한 문제: BUGG 웹사이트의 아이콘은 정확히 세련되거나 우아하지 않다;)
2017년 업데이트(7년 후) jagb는 Mikail Tuncs의 2011년 기사 "FARTing the Easy Way – Find And Replace Text"에 대한 코멘트에서 지적했다.
Joe Jobs가 코멘트(2020년 12월)에서 지적한 바와 같이 대체를 원하는 경우&A '', '따옴표', '따옴표', '따옴표', '따옴표'를.&되지 않습니다.
fart in.txt "&A" "B"
[Replace] - 문자열 치환을 사용하여 하위 문자열을 바꿉니다.설명:서브스트링을 다른 문자열로 대체하려면 문자열 치환 기능을 사용합니다.이 예에서는 문자열 변수 스트링 내의 모든 "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 "
메모 - 상위 JREPL에 대한 링크는 이 답변의 마지막에 업데이트를 참조하십시오.REP를 대체하는 BAT.박쥐
JREPL.BAT 7.0 이후에서는, Native Facebook을 경유해 Unicode(UTF-16LE)를 서포트하고 있습니다./UTFUTF-8은 ADO!!
저는 REP라는 작은 하이브리드 JScript/batch 유틸리티를 작성했습니다.명령줄 또는 배치 파일을 사용하여 ASCII(또는 확장 ASCII) 파일을 수정하는 데 매우 편리한 BAT.순수 네이티브 스크립트에서는 서드파티 실행 가능 파일을 설치할 필요가 없으며 XP 이후의 모든 최신 Windows 버전에서 작동합니다.특히 순수 배치 솔루션과 비교할 때 매우 빠릅니다.
REP.BAT는 stdin을 읽고 JScript regex 검색 및 치환을 수행한 후 결과를 stdout에 씁니다.
다음은 테스트에서 foo를 bar로 대체하는 간단한 예입니다.txt(REP을 전제로 합니다).BAT는 현재 폴더에 있거나 PATH 내 어딘가에 있습니다.
type test.txt|repl "foo" "bar" >test.txt.new
move /y test.txt.new test.txt
JScript regex 기능은 특히 검색 텍스트에서 캡처된 하위 문자열을 참조하는 대체 텍스트의 기능을 매우 강력하게 만듭니다.
유틸리티에는 강력한 기능을 제공하는 옵션이 많이 포함되어 있습니다.를 들어, 「」, 「」를 것.M ★★★★★★★★★★★★★★★★★」X옵션을 사용하면 바이너리 파일을 수정할 수 있습니다.M여러 줄 옵션을 사용하면 여러 줄에 걸쳐 검색할 수 있습니다.X은 대체할 수 합니다.Extended 치환 패턴 옵션은 대체 텍스트에 바이너리 값을 포함할 수 있는 이스케이프 시퀀스를 제공합니다.
유틸리티 전체가 순수 JScript로 작성될 수도 있지만 하이브리드 배치파일을 사용하면 유틸리티를 사용할 때마다 명시적으로 CSCRIPT를 지정할 필요가 없습니다.
여기 리플리케이션이 있습니다.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));
}
중요한 갱신
REP의 개발을 중지했습니다.BAT를 JREPL로 대체했습니다.BAT. 이 새로운 유틸리티는 모두 REP의 기능을 갖추고 있습니다.BAT 및 기타 기능:
- Unicode UTF-16LE는 네이티브 CSCRIPT Unicode 기능을 통해 지원되며 기타 문자 세트(UTF-8 포함)는 ADO를 통해 지원됩니다.
- 파일에서 직접 읽거나 파일에 직접 쓰기: 파이프, 리디렉션 또는 이동 명령이 필요하지 않습니다.
- 사용자 제공 JScript 통합
- unix tr과 유사한 번역 기능. regex 검색과 JScript 치환도 지원합니다.
- 일치하지 않는 텍스트 삭제
- 출력 행에 회선 번호를 붙입니다.
- 그리고 더...
항상 그렇듯이 스크립트에는 완전한 문서가 포함되어 있습니다.
기존의 사소한 솔루션은 이제 훨씬 더 단순해졌습니다.
jrepl "foo" "bar" /f test.txt /o -
JREPL의 현재 버전BAT는 DosTips에서 구할 수 있습니다.사용 예시와 개발 이력을 보려면 스레드의 후속 게시물을 모두 읽으십시오.
BatchSubstitute.bat dostips.com 에서는 순수 배치 파일을 사용한 검색 및 치환 예를 보여 줍니다.
하다, 하다, 하다, 하다를 조합해서 .FOR,FIND ★★★★★★★★★★★★★★★★★」CALL SET.
「」의 문자를 한 행."&<>]|^잘못 취급될 수 있습니다.
FNR 사용
하다를 사용하세요.fnr효용.에 비해 몇 가지 이점이 있습니다.fart:
- 정규 표현
- 옵션 GUI배치 파일에 넣을 명령줄 텍스트를 만드는 "명령줄 생성 버튼"이 있습니다.
- 여러 줄 패턴:GUI를 사용하면 여러 줄의 패턴으로 쉽게 작업할 수 있습니다.BUGG에서는 줄 바꿈을 수동으로 피해야 합니다.
- 텍스트 파일 인코딩을 선택할 수 있습니다.자동 검출 옵션도 있습니다.
여기서 FNR 다운로드: http://findandreplace.io/?z=코데플렉스
예: " " " :fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"
내장된 명령어로는 할 수 없는 것 같아요.Gnuwin32나 UnxUtils 같은 것을 다운로드하여sed명령어(또는 다운로드 전용):
sed -c s/FOO/BAR/g filename
파티에 늦은 거 알아..
개인적으로 저는 다음 사이트를 통해 솔루션이 마음에 듭니다.- 。
또한 중복 배제 기능을 광범위하게 사용하여 https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o에서 SMTP를 통해 매일 약 500개의 이메일을 전송할 수 있도록 지원합니다.
이 두 가지 모두 별도의 도구나 유틸리티 없이 기본적으로 작동합니다.
리페이서:
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으로 작업할 경우 부팅하여 사용할 수 있습니다.또는 Windows 10을 사용할 경우 (Linux 서브시스템에서) "Bash on Ubuntu on Windows"를 시작하고 를 사용합니다.
스트림 에디터이지만 다음 명령을 사용하여 파일을 직접 편집할 수 있습니다.
sed -i -e 's/foo/bar/g' filename
-i옵션은 파일 이름을 편집하기 위해 사용됩니다.-e를 나타냅니다.option은 실행 명령어입니다.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 파일로 만드는 방법을 찾을 수 없었습니다만... :- (
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
이 질문에는 Windows에서 동등한 sed를 요구하는 cmd.exe에 대한 sed like 유틸리티가 적용되는지 확인하십시오.이그제큐티브 요약:
- 배치 파일로 할 수 있지만, 예쁘지는 않다.
- exe를 설치 또는 복사하는 번거로움 없이 사용할 수 있는 많은 서드파티 실행 파일
- Windows 박스상에서 변경 없이 실행할 수 있는 것이 필요한 경우는, VBScript등을 사용해 실행할 수 있습니다.
조금 늦을지도 모르지만, 소프트웨어 승인을 받는 수고를 겪고 싶지 않기 때문에, 자주 같은 것을 찾고 있습니다.
그러나 보통 FOR 문을 다양한 형식으로 사용합니다.누군가가 검색 및 치환을 수행하는 유용한 배치 파일을 만들었습니다.여기 좀 보세요.제공된 배치 파일의 제한 사항을 이해하는 것이 중요합니다.따라서 이 답변의 소스 코드를 복사하지 않습니다.
파워셸 명령어는 마법처럼 기능합니다.
(
test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
)
합니다.search and replace Overflow 멤버에 되었습니다.dbenham ★★★★★★★★★★★★★★★★★」aacini를 사용합니다.native built-in jscriptWindows 의 windows 、 조 windows windows windows 。
다 theyrobust ★★★★★★★★★★★★★★★★★」very swift with large files또, 「」도 참조해 주세요.simpler텍스트의 기본 치환에 사용합니다. 다 있다Windows regular expression패턴 매칭
...
sed-like도우미 배치파일은 (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"★★★★★★★★★★★★★★★★★.
grep-like도우미 배치파일은 (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을 사용하다
사용하는 것이 좋습니다.sedWin32용 GNU 유틸리티에서 다음 사항에 유의해야 합니다.
- " " "
''사용하세요.""대신에sed -iWindows 에서는 동작하지 않습니다.파일 스와핑이 필요합니다.
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★sed 내의 .
sed -e "s/foo/bar/g" test.txt > tmp.txt && mv tmp.txt test.txt
.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"
"파일 내에서 텍스트를 검색하여 바꿉니다"와 같은 문제에 직면했습니다.단, 파일 이름과 검색/복원에 대해서는 regex를 사용해야 합니다.Powershell에 익숙하지 않아 나중에 사용하기 위해 검색을 저장하고 싶기 때문에 좀 더 "사용자 친화적인" 것이 필요합니다(GUI가 있는 경우 더 좋습니다).
그래서 구글을 검색하던 중 좋은 도구를 찾았습니다. FAR (Find And Replace) (방귀가 아닌)
이 작은 프로그램은 훌륭한 GUI를 갖추고 있으며 파일 이름 및 파일 내 검색을 위한 regex를 지원합니다.다만, 설정을 보존하려면 , 관리자로서 프로그램을 실행할 필요가 있습니다(적어도 Windows 7 에서는).
저는 부호화(UTF-8부터)를 변경하지 않도록 악센트를 유지합니다.유일한 방법은 디폴트 부호화 전후에 언급하는 것입니다.
powershell -Command "(gc 'My file.sql' -encoding "Default") -replace 'String 1', 'String 2' | Out-File -encoding "Default" 'My file.sql'"
@, @Rachel의 $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%"
이것은 배치 스크립팅이 잘 되지 않는 것의 하나입니다.
에 링크된 스크립트 morechilli는 일부 파일에서는 동작하지만 파이프나 앰퍼샌드 등의 문자가 포함된 파일에서는 동작하지 않습니다.
이 작업에는 VBScript가 더 적합합니다.예에 대해서는, 다음의 문서를 참조해 주세요.http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx
Cygwin(무료)을 다운로드하여 Windows 명령줄에서 unix-like 명령을 사용합니다.
최선의 선택: sed
Replace 및 Replace Filter 툴도 https://zoomicon.github.io/tranXform/ 에서 확인할 수 있습니다(소스 포함).두 번째는 필터입니다.
파일의 문자열을 대체하는 도구는 VBScript입니다(이전 버전의 Windows Script Host(WSH)를 실행하려면 Windows Script Host(WSH)가 필요합니다).
필터는 최신 Dellphi(또는 FreePascal/Lazarus)를 사용하여 재컴파일하지 않으면 Unicode에서 작동하지 않을 수 있습니다.
Powershell 명령어 -
파일의 내용을 가져와 다른 텍스트로 바꾼 다음 다른 파일에 저장
명령어 1 (Get-Content filename.xml)| 각 오브젝트 {$.replace("some_text","replace_text").replace("some_other_text","replace_text") } | Set-Content filename 2.xml
다른 파일을 원래 파일에 복사
명령어 2
Copy-Item - Path filename2.xml - Destination filename.xml - Pass스루
다른 하나의 파일 삭제
명령어 3
Remove-Item filename 2.xml
Windows 명령줄에서 사용할 수 있는 Aba Search and Replace의 작성자입니다.사용자 조작 없이 배치 치환을 수행할 수 있으며, 한 파일뿐만 아니라 여러 파일의 텍스트도 바꿀 수 있습니다.
제 도구를 사용해 보세요. 어떤 질문이든 기꺼이 답변해 드리겠습니다.
Visual C++에서 코딩하는 동안 여러 번 이 문제에 직면했습니다.Visual studio Find and Replace 유틸리티를 사용할 수 있습니다.폴더를 선택하고 해당 폴더의 파일 내용을 원하는 다른 텍스트로 바꿀 수 있습니다.
Visual Studio 아래:편집 -> [검색 및 치환(Find What)](검색 및 치환) 열려 있는 대화 상자에서 폴더를 선택하고 [검색 내용(Find What)](검색 내용) 및 [치환 대상(Replace With)](치환 대상) 상자에 입력합니다.이것이 도움이 되기를 바랍니다.
언급URL : https://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir
'programing' 카테고리의 다른 글
| StackPanel의 자 요소를 띄우려면 어떻게 해야 합니까? (0) | 2023.04.21 |
|---|---|
| 반복하는 동안 NSMutable Array에서 제거하는 가장 좋은 방법은 무엇입니까? (0) | 2023.04.21 |
| Is String.Contains()가 String보다 빠릅니다.Index Of()? (0) | 2023.04.21 |
| Azure 데이터베이스의 비밀번호 재설정 (0) | 2023.04.21 |
| 정밀도를 잃지 않고 Python Float를 문자열로 변환 (0) | 2023.04.21 |