Come puoi trovare e sostituire il testo in un file utilizzando l'ambiente della riga di comando di Windows?
-
09-06-2019 - |
Domanda
Sto scrivendo uno script di file batch utilizzando l'ambiente della riga di comando di Windows e desidero modificare ogni occorrenza di del testo in un file (es."FOO") con un altro (es."SBARRA").Qual è il modo più semplice per farlo?Qualche funzione integrata?
Soluzione
Molte delle risposte qui mi hanno aiutato a indicarmi la giusta direzione, tuttavia nessuna era adatta a me, quindi pubblico la mia soluzione.
Ho Windows 7, che viene fornito con PowerShell integrato.Ecco lo script che ho usato per trovare/sostituire tutte le occorrenze di testo in un file:
powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File myFile.txt"
Per spiegarlo:
powershell
avvia powershell.exe, incluso in Windows 7-Command "... "
è un argomento della riga di comando per powershell.exe contenente il comando da eseguire(gc myFile.txt)
legge il contenuto dimyFile.txt
(gc
è l'abbreviazione diGet-Content
comando)-replace 'foo', 'bar'
esegue semplicemente il comando di sostituzione per sostituirefoo
conbar
| Out-File myFile.txt
reindirizza l'output al filemyFile.txt
Powershell.exe dovrebbe già far parte della tua istruzione PATH, ma in caso contrario puoi aggiungerlo.La sua posizione sulla mia macchina è C:\WINDOWS\system32\WindowsPowerShell\v1.0
Altri suggerimenti
Se utilizzi una versione di Windows che supporta .Net 2.0, sostituirei la tua shell. PowerShell ti offre tutta la potenza di .Net dalla riga di comando.Ci sono anche molti comandi integrati.L'esempio seguente risolverà la tua domanda.Sto utilizzando i nomi completi dei comandi, ci sono alias più brevi, ma questo ti dà qualcosa per cui Google.
(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
Appena usato SCOREGGIA ("F ind UN nd R eplace T ext" utilità della riga di comando):
eccellente piccolo freeware per la sostituzione del testo all'interno di un ampio set di file.
I file di installazione sono su SourceForge.
Esempio di utilizzo:
fart.exe -p -r -c -- C:\tools\perl-5.8.9\* @@APP_DIR@@ C:\tools
visualizzerà in anteprima le sostituzioni da fare ricorsivamente nei file di questa distribuzione Perl.
Unico problema:l'icona del sito FART non è esattamente di buon gusto, raffinata o elegante ;)
Aggiornamento 2017 (7 anni dopo) jagb sottolinea nei commenti all'articolo del 2011 "SCORGARE nel modo più semplice: trova e sostituisci il testo" da Mikail Tunc
Sostituire - Sostituire una sottostringa usando la sostituzione della stringa Descrizione:Per sostituire una sottostringa con un'altra stringa utilizzare la funzione di sostituzione delle stringhe.L'esempio mostrato qui sostituisce tutte le occorrenze di errori di ortografia "teh" con "the" nella variabile stringa str.
set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%
Output dello script:
teh cat in teh hat
the cat in the hat
rif: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace
Crea il file 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
Per utilizzare questo script rivisto (che chiameremo replace.vbs) basta digitare un comando simile a questo dal prompt dei comandi:
cscript replace.vbs "C:\Scripts\Text.txt" "Jim " "James "
BatchSubstitute.bat
su dostips.com è un esempio di ricerca e sostituzione utilizzando un file batch puro.
Utilizza una combinazione di FOR
, FIND
E CALL SET
.
Righe contenenti caratteri tra "&<>]|^
potrebbero essere trattati in modo errato.
Nota - Assicurati di vedere l'aggiornamento alla fine di questa risposta per un collegamento al JREPL.BAT superiore che sostituisce REPL.BAT
JREPL.BAT 7.0 e versioni successive supporta nativamente unicode (UTF-16LE) tramite il /UTF
opzione, così come qualsiasi altro set di caratteri, incluso UTF-8, tramite ADO!!!!
Ho scritto una piccola utility ibrida JScript/batch chiamata REPL.BAT questo è molto comodo per modificare file ASCII (o ASCII esteso) tramite la riga di comando o un file batch.Lo script puramente nativo non richiede l'installazione di alcun eseguibile di terze parti e funziona su qualsiasi versione moderna di Windows da XP in poi.È anche molto veloce, soprattutto se paragonato alle soluzioni batch pure.
REPL.BAT legge semplicemente stdin, esegue una ricerca e sostituzione di regex JScript e scrive il risultato su stdout.
Ecco un banale esempio di come sostituire foo con bar in test.txt, presupponendo che REPL.BAT sia nella cartella corrente o, meglio ancora, da qualche parte all'interno del PATH:
type test.txt|repl "foo" "bar" >test.txt.new
move /y test.txt.new test.txt
Le funzionalità regex di JScript lo rendono molto potente, in particolare la capacità del testo sostitutivo di fare riferimento a sottostringhe catturate dal testo di ricerca.
Ho incluso una serie di opzioni nell'utilità che la rendono piuttosto potente.Ad esempio, combinando il M
E X
le opzioni consentono la modifica dei file binari!IL M
L'opzione multilinea consente ricerche su più righe.IL X
L'opzione del modello di sostituzione esteso fornisce sequenze di escape che consentono l'inclusione di qualsiasi valore binario nel testo sostitutivo.
L'intera utilità avrebbe potuto essere scritta come puro JScript, ma il file batch ibrido elimina la necessità di specificare esplicitamente CSCRIPT ogni volta che si desidera utilizzare l'utilità.
Ecco lo script REPL.BAT.La documentazione completa è incorporata nello script.
@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));
}
AGGIORNAMENTO IMPORTANTE
Ho interrotto lo sviluppo di REPL.BAT e l'ho sostituito con JREPL.BAT.Questa nuova utility ha tutte le stesse funzionalità di REPL.BAT, oltre a molto altro ancora:
- Supporto Unicode UTF-16LE tramite funzionalità unicode CSCRIPT native e qualsiasi altro set di caratteri (incluso UTF-8) tramite ADO.
- Leggere direttamente da/scrivere direttamente in un file:non sono necessari pipe, reindirizzamenti o comandi di spostamento.
- Incorpora JScript fornito dall'utente
- Funzione di traduzione simile a unix tr, solo che supporta anche la ricerca regex e la sostituzione JScript
- Scarta il testo non corrispondente
- Prefisso le righe di output con il numero di riga
- e altro ancora...
Come sempre, la documentazione completa è incorporata nello script.
La banale soluzione originale ora è ancora più semplice:
jrepl "foo" "bar" /f test.txt /o -
La versione corrente di JREPL.BAT è disponibile su DosTips.Leggi tutti i post successivi nel thread per vedere esempi di utilizzo e una cronologia dello sviluppo.
Usa FNR
Usa il fnr
utilità.Ha alcuni vantaggi rispetto a fart
:
- Espressioni regolari
- GUI opzionale.Dispone di un "pulsante Genera riga di comando" per creare testo della riga di comando da inserire nel file batch.
- Motivi multilinea:La GUI consente di lavorare facilmente con modelli multilinea.In FART dovresti sfuggire manualmente alle interruzioni di riga.
- Consente di selezionare la codifica del file di testo.Ha anche un'opzione di rilevamento automatico.
Scarica FNR qui: http://findandreplace.io/?z=codeplex
Esempio di utilizzo:fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"
Lo so, sono in ritardo per la festa..
Personalmente, mi piace la soluzione su:- http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace
Inoltre, utilizziamo ampiamente la funzione Dedupe per aiutarci a consegnare circa 500 e-mail al giorno tramite SMTP da:- https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o
ed entrambi funzionano in modo nativo senza la necessità di strumenti o utilità aggiuntivi.
SOSTITUTIVO:
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
DEDUPLICATORE (notare l'uso di -9 per un numero ABA):
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
Grazie!
Quando lavori con Git su Windows quindi accendi semplicemente git-bash
e utilizzare sed
.Oppure, quando si utilizza Windows 10, avviare "Bash su Ubuntu su Windows" (dal sottosistema Linux) e utilizzare sed
.
È un editor di stream, ma può modificare i file direttamente utilizzando il seguente comando:
sed -i -e 's/foo/bar/g' filename
-i
l'opzione viene utilizzata per modificare sul posto il nome del file.-e
l'opzione indica un comando da eseguire.s
viene utilizzato per sostituire l'espressione trovata "foo" con "bar" eg
viene utilizzato per sostituire eventuali corrispondenze trovate.
Nota di ereOn:
Se desideri sostituire una stringa solo nei file con versione di un repository Git, potresti voler utilizzare:
git ls-files <eventual subfolders & filters> | xargs sed -i -e 's/foo/bar/g'
che fa miracoli.
Ho usato Perl e funziona meravigliosamente.
perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" <fileName>
.orig è l'estensione che verrà aggiunta al file originale
Per un numero di file corrispondenti come *.html
for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x
Ho giocato con alcune delle risposte esistenti qui e preferisco la mia soluzione migliorata ...
type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }"
o se vuoi salvare nuovamente l'output in un file...
type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }" > outputFile.txt
Il vantaggio di ciò è che puoi reindirizzare l'output da qualsiasi programma.Esamineremo l'utilizzo delle espressioni regolari anche con questo.Tuttavia, non sono riuscito a capire come trasformarlo in un file BAT per un utilizzo più semplice ...:-(
Con il sostituto.bat
1) Con e?
opzione che valuterà sequenze di caratteri speciali come \n\r
e sequenze Unicode.In questo caso sostituirà quello citato "Foo"
E "Bar"
:
call replacer.bat "e?C:\content.txt" "\u0022Foo\u0022" "\u0022Bar\u0022"
2) Sostituzione semplice dove il Foo
E Bar
non sono citati.
call replacer.bat "C:\content.txt" "Foo" "Bar"
Ecco una soluzione che ho trovato funzionante su Win XP.Nel mio file batch in esecuzione, ho incluso quanto segue:
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
IL replace.bat
il file è il seguente.Non ho trovato un modo per includere quella funzione nello stesso file batch, perché il file %%a
la variabile sembra sempre fornire l'ultimo valore nel ciclo 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
Dare un'occhiata a Esiste un'utilità simile a sed per cmd.exe che richiedeva un equivalente sed sotto Windows, dovrebbe applicarsi anche a questa domanda.Sintesi:
- Può essere fatto in un file batch, ma non è carino
- Molti eseguibili di terze parti disponibili che lo faranno per te, se hai il lusso di installare o semplicemente copiare un exe
- Può essere fatto con VBScript o simili se hai bisogno di qualcosa che possa essere eseguito su una macchina Windows senza modifiche, ecc.
Potrebbe essere un po' tardi, ma cerco spesso cose simili, dal momento che non voglio sopportare la fatica di ottenere l'approvazione del software.
Tuttavia, di solito si utilizza l'istruzione FOR in varie forme.Qualcuno ha creato un utile file batch che esegue una ricerca e sostituzione.Dare un'occhiata Qui.È importante comprendere le limitazioni del file batch fornito.Per questo motivo non copio il codice sorgente in questa risposta.
Due file batch che forniscono search and replace
le funzioni sono state scritte dai membri di Stack Overflow dbenham
E aacini
utilizzando native built-in jscript
in Windows.
Sono entrambi robust
E very swift with large files
rispetto al semplice scripting batch e anche simpler
da utilizzare per la sostituzione di base del testo.Entrambi lo hanno fatto Windows regular expression
corrispondenza dei modelli.
Questo
sed-like
viene chiamato il file batch helperrepl.bat
(di dbenham).Esempio utilizzando il
L
interruttore letterale:echo This is FOO here|repl "FOO" "BAR" L echo and with a file: type "file.txt" |repl "FOO" "BAR" L >"newfile.txt"
Questo
grep-like
viene chiamato il file batch helperfindrepl.bat
(di aacini).Esempio in cui sono attive le espressioni regolari:
echo This is FOO here|findrepl "FOO" "BAR" echo and with a file: type "file.txt" |findrepl "FOO" "BAR" >"newfile.txt"
Entrambi diventano potenti utilità a livello di sistema when placed in a folder that is on the path
, oppure può essere utilizzato nella stessa cartella con un file batch o dal prompt cmd.
Entrambi lo hanno fatto case-insensitive
interruttori e anche molte altre funzioni.
Il comando Power Shell funziona come un incantesimo
(
test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
)
Ho appena riscontrato un problema simile: "Cerca e sostituisci testo all'interno dei file", ma con l'eccezione che sia per i nomi dei file che per la ricerca/sostituzione devo utilizzare regex.Poiché non ho familiarità con Powershell e desidero salvare le mie ricerche per un uso successivo, ho bisogno di qualcosa di più "user friendly" (preferibile se dotato di GUI).
Quindi, mentre cercavo su Google :) ho trovato un ottimo strumento: FAR (Trova e sostituisci) (non SCOREGGIA).
Quel piccolo programma ha una bella GUI e supporta le espressioni regolari per la ricerca nei nomi dei file e all'interno dei file.L'unico svantaggio è che se vuoi salvare le tue impostazioni devi eseguire il programma come amministratore (almeno su Win7).
Questa è una cosa che lo scripting batch semplicemente non fa bene.
Il copione morechilli linked to funzionerà per alcuni file, ma sfortunatamente si bloccherà su quelli che contengono caratteri come pipe e e commerciali.
VBScript è uno strumento integrato migliore per questa attività.Vedi questo articolo per un esempio:http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx
@Rachel ha dato un'ottima risposta, ma eccone una variante per leggere il contenuto su PowerShell $data
variabile.È quindi possibile manipolare facilmente il contenuto più volte prima di scriverlo su un file di output.Vedi anche come vengono forniti i valori su più righe nei file batch .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%"
Utilizza PowerShell in .bat - per Windows 7+
la codifica utf8 è facoltativa, utile per i siti web
@echo off
set ffile='myfile.txt'
set fold='FOO'
set fnew='BAR'
powershell -Command "(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8"
Preferisco usare sed
da Utilità GNU per Win32, occorre tenere presente quanto segue
- citazione singola
''
non funzionerà in Windows, usa""
Invecesed -i
non funzionerà in Windows, avrà bisogno di file scambio
Quindi il codice di lavoro di sed
per trovare e sostituire il testo in un file in Windows è il seguente
sed -e "s/foo/bar/g" test.txt > tmp.txt && mv tmp.txt test.txt
Scaricamento Cygwin (gratuito) e utilizza comandi simili a Unix nella riga di comando di Windows.
La soluzione migliore:sed
Puoi anche vedere gli strumenti Sostituisci e Sostituisci filtro su https://zoomicon.github.io/tranXform/ (fonte inclusa).Il secondo è un filtro.
Lo strumento che sostituisce le stringhe nei file è in VBScript (necessita di Windows Script Host [WSH] per essere eseguito nelle vecchie versioni di Windows)
Probabilmente il filtro non funziona con Unicode a meno che non venga ricompilato con l'ultimo Delphi (o con FreePascal/Lazarus)
Ho affrontato questo problema più volte durante la codifica in Visual C++.Se ce l'hai, puoi utilizzare l'utilità Trova e sostituisci di Visual Studio.Ti consente di selezionare una cartella e sostituire il contenuto di qualsiasi file in quella cartella con qualsiasi altro testo desideri.
In Visual Studio:Modifica -> Trova e sostituisci nella finestra di dialogo aperta, seleziona la cartella e compila "Trova cosa" e "sostituisci con" caselle.Spero che questo possa essere utile.