Jak można znaleźć i zastąpić tekst w pliku za pomocą środowiska wiersza poleceń systemu Windows?

Piszę skrypt pliku wsadowego używając środowiska wiersza poleceń systemu Windows i chcę zmienić każde wystąpienie jakiegoś tekstu w pliku (np. "FOO") z innym (ex. "BAR"). Jaki jest najprostszy sposób, aby to zrobić? Jakieś wbudowane funkcje?

Author: Ray Vega, 2008-09-13

26 answers

Jeśli używasz wersji systemu Windows, która obsługuje. Net 2.0, zamieniłbym Twoją powłokę. PowerShell daje pełną moc. Net z linii poleceń. Istnieje wiele komend wbudowanych, jak również. Poniższy przykład rozwiąże twoje pytanie. Używam pełnych nazw komend, są krótsze aliasy, ale to daje coś do Google.

(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
 176
Author: Mike Schall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-10 13:07:42

Wiele odpowiedzi pomogło mi wskazać właściwy kierunek, jednak żadna nie była dla mnie odpowiednia, więc zamieszczam moje rozwiązanie.

Mam Windows 7, który jest wyposażony w PowerShell wbudowany. Oto skrypt, którego użyłem do znalezienia / zastąpienia wszystkich instancji tekstu w pliku:

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

Aby to wyjaśnić:

  • powershell uruchamia powershell.exe, który jest zawarty w Windows 7
  • -Command "... " jest arg linii poleceń dla powershell.exe zawierający polecenie do run
  • (gc myFile.txt) odczytuje zawartość myFile.txt (gc jest skrótem od polecenia Get-Content)
  • -replace 'foo', 'bar' po prostu uruchamia polecenie replace, aby zastąpić foo przez bar
  • | Out-File myFile.txt przekierowuje wyjście do pliku myFile.txt
Powershell.exe powinien być już częścią twojej instrukcji PATH, ale jeśli nie, możesz ją dodać. Lokalizacja na mojej maszynie to C:\WINDOWS\system32\WindowsPowerShell\v1.0
 189
Author: Rachel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-08 15:01:35

Po prostu używane Bąk ("F ind A nd R eplace T ext " narzędzie wiersza poleceń):
doskonałe małe freeware do wymiany tekstu w dużym zestawie plików.

Pliki konfiguracyjne znajdują się na SourceForge.

Przykład użycia:

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

Wyświetli podgląd zamienników, które będą wykonywane rekurencyjnie w plikach tej dystrybucji Perla.

Jedyny problem: ikona strony FART nie jest do końca gustowna, dopracowana lub eleganckie;)


Aktualizacja 2017 (7 lat później) jagb wskazuje w komentarzach do artykułu z 2011 roku "Pierdzenie w łatwy sposób-znajdź i zamień tekst " z Mikail Tunç

 149
Author: VonC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:21

Replace-Zastąp podłańcuch za pomocą substytucji łańcuchów Opis: aby zastąpić łańcuch znaków innym łańcuchem, użyj funkcji zastępowania łańcuchów. Pokazany tutaj przykład zastępuje wszystkie wystąpienia "teh" błędnych pisowni przez "the" W Zmiennej łańcuchowej str.

set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%

Wyjście Skryptu:

teh cat in teh hat
the cat in the hat

Ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

 114
Author: Bill Richardson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-26 13:09:32

Utwórz plik 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

Aby użyć tego poprawionego skryptu (który nazwiemy replace.vbs) wystarczy wpisać polecenie podobne do tego z wiersza polecenia:

cscript replace.vbs "C:\Scripts\Text.txt" "Jim " "James "

 51
Author: user459118,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-12 03:48:43

BatchSubstitute.bat on dostips.com {[7] } jest przykładem wyszukiwania i zastępowania przy użyciu czystego pliku wsadowego.

Używa kombinacji FOR, FIND i CALL SET.

Linie zawierające znaki wśród "&<>]|^ mogą być traktowane nieprawidłowo.


 48
Author: morechilli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-11 08:33:08

uwaga - pamiętaj, aby zobaczyć aktualizację na końcu tej odpowiedzi, aby znaleźć link do nadrzędnego JREPL.BAT, który zastępuje REPL.BAT
JREPL.BAT 7.0 i nowsze natywnie obsługuje unicode (UTF-16LE) poprzez opcję /UTF, a także każdy inny zestaw znaków, w tym UTF-8, poprzez ADO!!!!


Napisałem małe hybrydowe narzędzie JScript / batch o nazwie REPL.BAT , który jest bardzo wygodny do modyfikowania ASCII (lub rozszerzonego ASCII) plików za pomocą wiersza poleceń lub pliku wsadowego. Czysto natywny skrypt nie wymaga instalacji żadnej wykonywalnej strony trzeciej i działa na każdej nowoczesnej wersji systemu Windows od XP. Jest również bardzo szybki, szczególnie w porównaniu do czystych rozwiązań wsadowych.

REPL.BAT po prostu odczytuje stdin, wykonuje JScript regex search and replace i zapisuje wynik na stdout.

Oto trywialny przykład zamiany foo na bar w teście.txt, zakładając REPL.Nietoperz jest w Twoim katalog bieżący, albo jeszcze lepiej, gdzieś w twojej ścieżce:

type test.txt|repl "foo" "bar" >test.txt.new
move /y test.txt.new test.txt

Funkcje regex języka JScript sprawiają, że jest on bardzo wydajny, zwłaszcza zdolność zastępczego tekstu do odwoływania się do przechwyconych podłańcuchów z szukanego tekstu.

Włączyłem wiele opcji w narzędziu, które czynią go dość potężnym. Na przykład połączenie opcji M i X umożliwia modyfikację plików binarnych! Opcja M Multi-line umożliwia wyszukiwanie w wielu wierszach. The X eXtended opcja substitution pattern zapewnia sekwencje specjalne, które umożliwiają włączenie dowolnej wartości binarnej do tekstu zastępczego.

Całe narzędzie mogło być napisane jako czysty JScript, ale Hybrydowy plik wsadowy eliminuje potrzebę jawnego określania CSCRIPT za każdym razem, gdy chcesz użyć tego narzędzia.

Oto REPL.Skrypt nietoperza. Pełna dokumentacja jest osadzona w skrypcie.

@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));
}


WAŻNA AKTUALIZACJA

Przestałem rozwój REPL.BAT, i zastąpił go JREPL.BAT. To nowsze narzędzie ma taką samą funkcjonalność jak REPL.BAT, plus dużo więcej:

  • obsługa Unicode UTF-16LE poprzez natywne możliwości CSCRIPT unicode oraz wszelkie inne zestawy znaków (w tym UTF-8) poprzez ADO.
  • odczyt bezpośrednio z / zapis bezpośrednio do pliku: nie ma potrzeby stosowania rur, przekierowania ani polecenia move.
  • include user supplied JScript
  • tłumaczenie podobne do unix tr, tylko że również obsługuje wyszukiwanie regex i JScript replace
  • Odrzuć nie pasujący tekst
  • prefiks linii wyjściowych z numerem linii
  • i więcej...

Jak zawsze, pełna dokumentacja jest osadzona w skrypcie.

Oryginalne trywialne rozwiązanie jest teraz jeszcze prostsze:

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

Aktualna wersja JREPL.BAT jest dostępny w DosTips . Przeczytaj wszystkie kolejne posty w wątku, aby zobaczyć przykłady użycia i historię rozwoju.

 41
Author: dbenham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-09 16:50:07

Użyj FNR

Użyj narzędzia fnr. Ma pewne zalety nad fart:

  • wyrażenia regularne
  • opcjonalny GUI. Posiada "Generuj przycisk wiersza poleceń" do tworzenia tekstu wiersza poleceń do umieszczenia w pliku wsadowym.
  • wzorce Wielowierszowe: GUI pozwala na łatwą pracę z wzorcami wielowierszowymi. W Bąku trzeba by ręcznie uniknąć przerw w linii.
  • pozwala wybrać kodowanie plików tekstowych. Posiada również opcję automatycznego wykrywania.

Pobierz FNR tutaj: http://findandreplace.codeplex.com/

Przykład użycia: fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"

 29
Author: Aman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-08 11:48:20

Nie sądzę, żeby można było to zrobić za pomocą wbudowanych komend. Proponuję pobrać coś w stylu Gnuwin32 lub UnxUtils i użyć komendy sed (lub tylko pobrać sed):

sed -c s/FOO/BAR/g filename
 24
Author: Ferruccio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-25 16:24:18

Wiem, że jestem spóźniona na imprezę..

Osobiście podoba mi się rozwiązanie na: - http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

Używamy również szeroko funkcji Dedupe, aby pomóc nam dostarczać około 500 e-maili dziennie za pośrednictwem SMTP z: - https://groups.google.com/forum/#! topic / alt. msdos.batch. nt/sj8IUhMOq6o

I oba te działają natywnie bez dodatkowych narzędzi lub narzędzi potrzebne.

Zamiennik:

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

DEDUPLIKATOR (zwróć uwagę na użycie -9 dla liczby 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
Dzięki!
 17
Author: Leptonator,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-05 13:57:06

Kiedy pracujesz z Git na Windows następnie po prostu odpal git-bash i użycie sed. Lub, gdy używasz systemu Windows 10, Uruchom "Bash on Ubuntu on Windows" (z podsystemu Linux) i użyj sed.

Jest edytorem strumienia, ale może edytować pliki bezpośrednio za pomocą następującego polecenia:

sed -i -e 's/foo/bar/g' filename
  • -i opcja jest używana do edycji w miejscu nazwy pliku.
  • {[5] } opcja wskazuje polecenie do uruchomienia.
    • s jest używane do zastąpienia znalezionego wyrażenia " foo "przez " bar", a g jest używane do zastąpienia znalezionych dopasowań.

Uwaga autorstwa ereona:

Jeśli chcesz zastąpić ciąg znaków Tylko w wersjonowanych plikach repozytorium Git, możesz użyć:

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

Co czyni cuda.
 13
Author: Jens A. Koch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-07 22:31:27

Użyłem Perla i to działa cudownie.

perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" <fileName>

.orig jest rozszerzeniem, które doda do oryginalnego pliku

Dla wielu pasujących plików, takich jak *.html

for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x
 12
Author: Faisal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-18 22:40:43

Pobawiłem się niektórymi z istniejących odpowiedzi tutaj i wolę moje ulepszone rozwiązanie...

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }"

Lub jeśli chcesz zapisać wyjście ponownie do pliku...

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }" > outputFile.txt

Zaletą tego jest to, że można przesyłać dane wyjściowe z dowolnego programu. Zajmie się również używaniem wyrażeń regularnych. Nie mogłem jednak wymyślić, jak przekształcić go w plik BAT dla łatwiejszego użycia... :-(

 12
Author: Simon East,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-08 00:00:04

Z zamiennikiem.bat

1) z opcją e?, która będzie oceniać sekwencje znaków specjalnych, takie jak \n\r i sekwencje unicode. W tym przypadku zastąpi cytowane "Foo" i "Bar":

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

2) proste zastąpienie gdzie Foo i Bar nie są cytowane.

call replacer.bat "C:\content.txt" "Foo" "Bar"
 11
Author: npocmaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-15 13:05:21

Oto rozwiązanie, które znalazłem działa na Win XP. W moim uruchomionym pliku wsadowym umieściłem:

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

Plik replace.bat jest jak poniżej. Nie znalazłem sposobu na włączenie tej funkcji do tego samego pliku wsadowego, ponieważ zmienna %%a zawsze wydaje się dawać ostatnią wartość w pętli 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
 10
Author: Chad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-11 08:36:09

Spójrz na czy jest jakieś narzędzie typu sed dla cmd.exe , który poprosił o odpowiednik sed pod Windows, powinien również odnosić się do tego pytania. Streszczenie:

  • można to zrobić w pliku wsadowym, ale nie jest to ładne
  • Wiele dostępnych plików wykonywalnych innych firm, które zrobią to za Ciebie, jeśli masz luksus instalowania lub kopiowania przez exe
  • można to zrobić za pomocą VBScript lub podobnego, jeśli potrzebujesz czegoś zdolnego do uruchomienia na Windows box bez modyfikacja itp.
 7
Author: Jay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:21

Może być trochę późno, ale często szukam podobnych rzeczy, ponieważ nie chcę przechodzić przez ból uzyskania zatwierdzenia oprogramowania.

Jednak zwykle używa się instrukcji FOR w różnych formach. Ktoś stworzył przydatny plik wsadowy, który wyszukuje i zastępuje. Zobacz TUTAJ . Ważne jest, aby zrozumieć ograniczenia dostarczonego pliku wsadowego. Z tego powodu nie kopiuję kodu źródłowego w tej odpowiedzi.

 4
Author: Peter Schuetze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-12-23 16:20:39

Dwa pliki wsadowe dostarczające funkcje search and replace zostały napisane przez członków Stack Overflow dbenham i aacini przy użyciu native built-in jscript w systemie Windows.

Są zarówno robust, jak i very swift with large files w porównaniu do zwykłego skryptowania wsadowego, a także simpler do podstawowego zastępowania tekstu. Oba mają Windows regular expression dopasowanie wzorca.

======================================================================================

1) Ten sed-like helper plik wsadowy nazywa się repl.bat (przez dbenham) - Pobierz z: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

Przykład użycia literalnego przełącznika 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) ten grep-like helper plik wsadowy nazywa się findrepl.bat (by aacini) - Pobierz z: https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat

Przykład zawierający wyrażenia regularne aktywny:

echo This is FOO here|findrepl "FOO" "BAR" 
echo and with a file:
type "file.txt" |findrepl "FOO" "BAR" >"newfile.txt"

======================================================================================

Oba stają się potężnymi narzędziami systemowymi when placed in a folder that is on the path, lub mogą być używane w tym samym folderze z plikiem wsadowym lub z monitu cmd.

Oba mają case-insensitive przełączniki i wiele innych funkcji.

 4
Author: foxidrive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-22 13:18:51

Polecenie Power shell działa jak urok

(
test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
)
 3
Author: kool_guy_here,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-08 10:58:07

Właśnie napotkałem podobny problem - "Szukaj i zamień tekst w plikach" , ale z tym wyjątkiem, że dla obu nazw plików i wyszukiwania/repalce muszę użyć regex. Ponieważ nie jestem zaznajomiony z Powershell i chcesz zapisać moje wyszukiwania do późniejszego wykorzystania potrzebuję czegoś bardziej "przyjazny dla użytkownika" (najlepiej, jeśli ma GUI).

Tak więc podczas googlowania :) znalazłem świetne narzędzie- FAR (Find And Replace) (nie pierdnięcie).

Ten mały program ma ładny GUI i obsługuje regex do wyszukiwania w nazwy plików i wewnątrz plików. Jedyną wadą jest to, że jeśli chcesz zapisać swoje ustawienia, musisz uruchomić program jako administrator (przynajmniej na Win7).

 3
Author: madcorp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-04 15:25:33

To jest jedna rzecz, która Skrypty wsadowe po prostu nie działa dobrze.

Skrypt morechilli podlinkowany do będzie działał dla niektórych plików, ale niestety będzie się dusił na tych, które zawierają znaki takie jak pipes i ampersands.

VBScript jest lepiej wbudowanym narzędziem do tego zadania. Zobacz ten artykuł dla przykładu: http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx

 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-17 17:58:08

@Rachel dała doskonałą odpowiedź, ale tutaj jest jego odmiana do odczytu treści do zmiennej powershell $data. Następnie można łatwo manipulować zawartością wiele razy przed zapisaniem do pliku wyjściowego. Zobacz także, jak wartości Wielowierszowe są podane w a .pliki wsadowe 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%"
 2
Author: Whome,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-15 21:21:51

Użyj powershell w .bat - Dla Windows 7 +

Kodowanie utf8 jest opcjonalne, dobre dla stron www

@echo off
set ffile='myfile.txt'
set fold='FOO'
set fnew='BAR'
powershell -Command "(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8"
 1
Author: Wagner Pereira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-17 01:12:44

Pobierz Cygwin (za darmo) i używaj uniksopodobnych poleceń w wierszu poleceń systemu Windows.

Twój najlepszy zakład: sed

 0
Author: jm.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-25 17:49:36

Można również zobaczyć narzędzia Replace i ReplaceFilter na https://zoomicon.github.io/tranXform / (Źródło włączone). Drugi to filtr.

Narzędzie, które zastępuje ciągi znaków w plikach, jest w języku VBScript (wymaga Windows Script Host [WSH] do uruchomienia w starych wersjach systemu Windows)

Filtr prawdopodobnie nie działa z Unicode, chyba że przekompilujesz z najnowszym Delphi (lub z FreePascal/Lazarus)

 0
Author: George Birbilis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-05 14:46:08

Miałem do czynienia z tym problemem kilka razy podczas kodowania w Visual C++. Jeśli go posiadasz, możesz użyć narzędzia Visual studio Find and Replace. Pozwala wybrać folder i zastąpić zawartość dowolnego pliku w tym folderze innym tekstem, który chcesz.

Pod Visual Studio: Edycja - > Znajdź i zamień W otwartym oknie wybierz folder i wypełnij pola "Znajdź co" i "zamień na". Mam nadzieję, że to będzie pomocne.

 -5
Author: Nadjib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-25 15:55:06