كيف يمكنك البحث عن النص واستبداله في ملف باستخدام بيئة سطر أوامر Windows؟

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

سؤال

أنا أكتب برنامج نصي لملف دفعي باستخدام بيئة سطر أوامر Windows وأريد تغيير كل تكرار لبعض النص في ملف (على سبيل المثال."FOO") مع شخص آخر (على سبيل المثال."حاجِز").ما هي أبسط طريقة للقيام بذلك؟أي وظائف مدمجة؟

هل كانت مفيدة؟

المحلول

لقد ساعدتني الكثير من الإجابات هنا في توجيهي في الاتجاه الصحيح، ولكن لم تكن أي منها مناسبة لي، لذلك أقوم بنشر الحل الخاص بي.

لدي نظام التشغيل Windows 7، والذي يأتي مزودًا ببرنامج PowerShell المدمج.إليك البرنامج النصي الذي استخدمته للعثور على/استبدال جميع مثيلات النص في الملف:

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

لشرح ذلك:

  • powershell يبدأ تشغيل powershell.exe، المضمن في نظام التشغيل Windows 7
  • -Command "... " عبارة عن وسيطة سطر أوامر لـ powershell.exe تحتوي على الأمر المطلوب تشغيله
  • (gc myFile.txt) يقرأ محتوى myFile.txt (gc قصير بالنسبة ل Get-Content يأمر)
  • -replace 'foo', 'bar' ببساطة يقوم بتشغيل أمر الاستبدال للاستبدال foo مع bar
  • | Out-File myFile.txt أنابيب الإخراج إلى الملف myFile.txt

يجب أن يكون Powershell.exe جزءًا من عبارة PATH بالفعل، ولكن إذا لم يكن الأمر كذلك، فيمكنك إضافته.موقعه على الجهاز الخاص بي هو C:\WINDOWS\system32\WindowsPowerShell\v1.0

نصائح أخرى

إذا كنت تستخدم إصدار Windows الذي يدعم .Net 2.0، فسوف أقوم باستبدال الصدفة الخاصة بك. بوويرشيل يمنحك القوة الكاملة لـ .Net من سطر الأوامر.هناك العديد من الأوامر المضمنة أيضًا.المثال أدناه سوف يحل سؤالك.أنا أستخدم الأسماء الكاملة للأوامر، وهناك أسماء مستعارة أقصر، ولكن هذا يمنحك شيئًا لـ Google.

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

تستخدم فقط ضرطة ("F إنديانا أ اختصار الثاني ر eplace ت تحويلة" فائدة سطر الأوامر):
برنامج مجاني صغير ممتاز لاستبدال النص ضمن مجموعة كبيرة من الملفات.

ملفات الإعداد موجودة على SourceForge.

مثال الاستخدام:

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

سيقوم بمعاينة البدائل للقيام بها بشكل متكرر في ملفات توزيع Perl هذا.

المشكلة الوحيدة:أيقونة موقع FART ليست حسنة الذوق أو راقية أو أنيقة تمامًا؛)


تحديث 2017 (بعد 7 سنوات) Jagb يشير الى في التعليقات لمقالة 2011 "إطلاق الريح بالطريقة السهلة - البحث عن النص واستبداله" من ميكائيل تونش

استبدال - استبدل سلسلة فرعية باستخدام وصف استبدال السلسلة:لاستبدال سلسلة فرعية بسلسلة أخرى، استخدم ميزة استبدال السلسلة.يستبدل المثال الموضح هنا كافة تكرارات الأخطاء الإملائية "teh" بـ "the" في متغير السلسلة str.

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

إخراج البرنامج النصي:

teh cat in teh hat
the cat in the hat

المرجع: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

إنشاء ملف استبدال.vbs:

Const ForReading = 1    
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText  'WriteLine adds extra CR/LF
objFile.Close

لاستخدام هذا البرنامج النصي المعدل (والذي سنسميه استبدال.vbs) فقط اكتب أمرًا مشابهًا لذلك من موجه الأوامر:

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

BatchSubstitute.bat على dostips.com هو مثال للبحث والاستبدال باستخدام ملف دفعي خالص.

ويستخدم مزيج من FOR, FIND و CALL SET.

الأسطر التي تحتوي على أحرف بين "&<>]|^ قد يتم التعامل معها بشكل غير صحيح.


ملحوظة - تأكد من رؤية التحديث في نهاية هذه الإجابة للحصول على رابط إلى JREPL.BAT المتميز الذي يحل محل REPL.BAT
JREPL.BAT 7.0 وما فوق يدعم أصلاً يونيكود (UTF-16LE) عبر /UTF الخيار، بالإضافة إلى أي مجموعة أحرف أخرى، بما في ذلك UTF-8، عبر ADO!!!!


لقد قمت بكتابة أداة مساعدة JScript/batch صغيرة تسمى REPL.BAT يعد هذا مناسبًا جدًا لتعديل ملفات ASCII (أو ASCII الموسعة) عبر سطر الأوامر أو ملف دفعي.لا يتطلب البرنامج النصي الأصلي تمامًا تثبيت أي جهة خارجية قابلة للتنفيذ، ويعمل على أي إصدار Windows حديث بدءًا من XP وما بعده.كما أنها سريعة جدًا، خاصة عند مقارنتها بالحلول الدفعية النقية.

يقرأ REPL.BAT ببساطة stdin، ويقوم بإجراء بحث واستبدال JScript regex، ويكتب النتيجة إلى stdout.

فيما يلي مثال بسيط لكيفية استبدال foo بـ bar في ملف test.txt، بافتراض أن REPL.BAT موجود في المجلد الحالي لديك، أو الأفضل من ذلك، في مكان ما داخل المسار الخاص بك:

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

إن إمكانات JScript regex تجعله قويًا جدًا، خاصة قدرة النص البديل على الإشارة إلى السلاسل الفرعية الملتقطة من نص البحث.

لقد قمت بتضمين عدد من الخيارات في الأداة المساعدة التي تجعلها قوية جدًا.على سبيل المثال، الجمع بين M و X خيارات تمكن من تعديل الملفات الثنائية!ال M خيار متعدد الأسطر يسمح بالبحث عبر أسطر متعددة.ال X يوفر خيار نمط الاستبدال الموسع تسلسلات هروب تمكن من تضمين أي قيمة ثنائية في النص البديل.

كان من الممكن كتابة الأداة المساعدة بأكملها كـ JScript خالص، لكن الملف الدفعي المختلط يلغي الحاجة إلى تحديد CSCRIPT بشكل صريح في كل مرة تريد فيها استخدام الأداة المساعدة.

هنا هو البرنامج النصي REPL.BAT.يتم تضمين الوثائق الكاملة داخل البرنامج النصي.

@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment

::************ Documentation ***********
::REPL.BAT version 6.2
:::
:::REPL  Search  Replace  [Options  [SourceVar]]
:::REPL  /?[REGEX|REPLACE]
:::REPL  /V
:::
:::  Performs a global regular expression search and replace operation on
:::  each line of input from stdin and prints the result to stdout.
:::
:::  Each parameter may be optionally enclosed by double quotes. The double
:::  quotes are not considered part of the argument. The quotes are required
:::  if the parameter contains a batch token delimiter like space, tab, comma,
:::  semicolon. The quotes should also be used if the argument contains a
:::  batch special character like &, |, etc. so that the special character
:::  does not need to be escaped with ^.
:::
:::  If called with a single argument of /?, then prints help documentation
:::  to stdout. If a single argument of /?REGEX, then opens up Microsoft's
:::  JScript regular expression documentation within your browser. If a single
:::  argument of /?REPLACE, then opens up Microsoft's JScript REPLACE
:::  documentation within your browser.
:::
:::  If called with a single argument of /V, case insensitive, then prints
:::  the version of REPL.BAT.
:::
:::  Search  - By default, this is a case sensitive JScript (ECMA) regular
:::            expression expressed as a string.
:::
:::            JScript regex syntax documentation is available at
:::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
:::  Replace - By default, this is the string to be used as a replacement for
:::            each found search expression. Full support is provided for
:::            substituion patterns available to the JScript replace method.
:::
:::            For example, $& represents the portion of the source that matched
:::            the entire search pattern, $1 represents the first captured
:::            submatch, $2 the second captured submatch, etc. A $ literal
:::            can be escaped as $$.
:::
:::            An empty replacement string must be represented as "".
:::
:::            Replace substitution pattern syntax is fully documented at
:::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
:::  Options - An optional string of characters used to alter the behavior
:::            of REPL. The option characters are case insensitive, and may
:::            appear in any order.
:::
:::            A - Only print altered lines. Unaltered lines are discarded.
:::                If the S options is present, then prints the result only if
:::                there was a change anywhere in the string. The A option is
:::                incompatible with the M option unless the S option is present.
:::
:::            B - The Search must match the beginning of a line.
:::                Mostly used with literal searches.
:::
:::            E - The Search must match the end of a line.
:::                Mostly used with literal searches.
:::
:::            I - Makes the search case-insensitive.
:::
:::            J - The Replace argument represents a JScript expression.
:::                The expression may access an array like arguments object
:::                named $. However, $ is not a true array object.
:::
:::                The $.length property contains the total number of arguments
:::                available. The $.length value is equal to n+3, where n is the
:::                number of capturing left parentheses within the Search string.
:::
:::                $[0] is the substring that matched the Search,
:::                $[1] through $[n] are the captured submatch strings,
:::                $[n+1] is the offset where the match occurred, and
:::                $[n+2] is the original source string.
:::
:::                Arguments $[0] through $[10] may be abbreviated as
:::                $1 through $10. Argument $[11] and above must use the square
:::                bracket notation.
:::
:::            L - The Search is treated as a string literal instead of a
:::                regular expression. Also, all $ found in the Replace string
:::                are treated as $ literals.
:::
:::            M - Multi-line mode. The entire contents of stdin is read and
:::                processed in one pass instead of line by line, thus enabling
:::                search for \n. This also enables preservation of the original
:::                line terminators. If the M option is not present, then every
:::                printed line is terminated with carriage return and line feed.
:::                The M option is incompatible with the A option unless the S
:::                option is also present.
:::
:::                Note: If working with binary data containing NULL bytes,
:::                      then the M option must be used.
:::
:::            S - The source is read from an environment variable instead of
:::                from stdin. The name of the source environment variable is
:::                specified in the next argument after the option string. Without
:::                the M option, ^ anchors the beginning of the string, and $ the
:::                end of the string. With the M option, ^ anchors the beginning
:::                of a line, and $ the end of a line.
:::
:::            V - Search and Replace represent the name of environment
:::                variables that contain the respective values. An undefined
:::                variable is treated as an empty string.
:::
:::            X - Enables extended substitution pattern syntax with support
:::                for the following escape sequences within the Replace string:
:::
:::                \\     -  Backslash
:::                \b     -  Backspace
:::                \f     -  Formfeed
:::                \n     -  Newline
:::                \q     -  Quote
:::                \r     -  Carriage Return
:::                \t     -  Horizontal Tab
:::                \v     -  Vertical Tab
:::                \xnn   -  Extended ASCII byte code expressed as 2 hex digits
:::                \unnnn -  Unicode character expressed as 4 hex digits
:::
:::                Also enables the \q escape sequence for the Search string.
:::                The other escape sequences are already standard for a regular
:::                expression Search string.
:::
:::                Also modifies the behavior of \xnn in the Search string to work
:::                properly with extended ASCII byte codes.
:::
:::                Extended escape sequences are supported even when the L option
:::                is used. Both Search and Replace support all of the extended
:::                escape sequences if both the X and L opions are combined.
:::
:::  Return Codes:  0 = At least one change was made
:::                     or the /? or /V option was used
:::
:::                 1 = No change was made
:::
:::                 2 = Invalid call syntax or incompatible options
:::
:::                 3 = JScript runtime error, typically due to invalid regex
:::
::: REPL.BAT was written by Dave Benham, with assistance from DosTips user Aacini
::: to get \xnn to work properly with extended ASCII byte codes. Also assistance
::: from DosTips user penpen diagnosing issues reading NULL bytes, along with a
::: workaround. REPL.BAT was originally posted at:
::: http://www.dostips.com/forum/viewtopic.php?f=3&t=3855
:::

::************ Batch portion ***********
@echo off
if .%2 equ . (
  if "%~1" equ "/?" (
    <"%~f0" cscript //E:JScript //nologo "%~f0" "^:::" "" a
    exit /b 0
  ) else if /i "%~1" equ "/?regex" (
    explorer "http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx"
    exit /b 0
  ) else if /i "%~1" equ "/?replace" (
    explorer "http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx"
    exit /b 0
  ) else if /i "%~1" equ "/V" (
    <"%~f0" cscript //E:JScript //nologo "%~f0" "^::(REPL\.BAT version)" "$1" a
    exit /b 0
  ) else (
    call :err "Insufficient arguments"
    exit /b 2
  )
)
echo(%~3|findstr /i "[^SMILEBVXAJ]" >nul && (
  call :err "Invalid option(s)"
  exit /b 2
)
echo(%~3|findstr /i "M"|findstr /i "A"|findstr /vi "S" >nul && (
  call :err "Incompatible options"
  exit /b 2
)
cscript //E:JScript //nologo "%~f0" %*
exit /b %errorlevel%

:err
>&2 echo ERROR: %~1. Use REPL /? to get help.
exit /b

************* JScript portion **********/
var rtn=1;
try {
  var env=WScript.CreateObject("WScript.Shell").Environment("Process");
  var args=WScript.Arguments;
  var search=args.Item(0);
  var replace=args.Item(1);
  var options="g";
  if (args.length>2) options+=args.Item(2).toLowerCase();
  var multi=(options.indexOf("m")>=0);
  var alterations=(options.indexOf("a")>=0);
  if (alterations) options=options.replace(/a/g,"");
  var srcVar=(options.indexOf("s")>=0);
  if (srcVar) options=options.replace(/s/g,"");
  var jexpr=(options.indexOf("j")>=0);
  if (jexpr) options=options.replace(/j/g,"");
  if (options.indexOf("v")>=0) {
    options=options.replace(/v/g,"");
    search=env(search);
    replace=env(replace);
  }
  if (options.indexOf("x")>=0) {
    options=options.replace(/x/g,"");
    if (!jexpr) {
      replace=replace.replace(/\\\\/g,"\\B");
      replace=replace.replace(/\\q/g,"\"");
      replace=replace.replace(/\\x80/g,"\\u20AC");
      replace=replace.replace(/\\x82/g,"\\u201A");
      replace=replace.replace(/\\x83/g,"\\u0192");
      replace=replace.replace(/\\x84/g,"\\u201E");
      replace=replace.replace(/\\x85/g,"\\u2026");
      replace=replace.replace(/\\x86/g,"\\u2020");
      replace=replace.replace(/\\x87/g,"\\u2021");
      replace=replace.replace(/\\x88/g,"\\u02C6");
      replace=replace.replace(/\\x89/g,"\\u2030");
      replace=replace.replace(/\\x8[aA]/g,"\\u0160");
      replace=replace.replace(/\\x8[bB]/g,"\\u2039");
      replace=replace.replace(/\\x8[cC]/g,"\\u0152");
      replace=replace.replace(/\\x8[eE]/g,"\\u017D");
      replace=replace.replace(/\\x91/g,"\\u2018");
      replace=replace.replace(/\\x92/g,"\\u2019");
      replace=replace.replace(/\\x93/g,"\\u201C");
      replace=replace.replace(/\\x94/g,"\\u201D");
      replace=replace.replace(/\\x95/g,"\\u2022");
      replace=replace.replace(/\\x96/g,"\\u2013");
      replace=replace.replace(/\\x97/g,"\\u2014");
      replace=replace.replace(/\\x98/g,"\\u02DC");
      replace=replace.replace(/\\x99/g,"\\u2122");
      replace=replace.replace(/\\x9[aA]/g,"\\u0161");
      replace=replace.replace(/\\x9[bB]/g,"\\u203A");
      replace=replace.replace(/\\x9[cC]/g,"\\u0153");
      replace=replace.replace(/\\x9[dD]/g,"\\u009D");
      replace=replace.replace(/\\x9[eE]/g,"\\u017E");
      replace=replace.replace(/\\x9[fF]/g,"\\u0178");
      replace=replace.replace(/\\b/g,"\b");
      replace=replace.replace(/\\f/g,"\f");
      replace=replace.replace(/\\n/g,"\n");
      replace=replace.replace(/\\r/g,"\r");
      replace=replace.replace(/\\t/g,"\t");
      replace=replace.replace(/\\v/g,"\v");
      replace=replace.replace(/\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}/g,
        function($0,$1,$2){
          return String.fromCharCode(parseInt("0x"+$0.substring(2)));
        }
      );
      replace=replace.replace(/\\B/g,"\\");
    }
    search=search.replace(/\\\\/g,"\\B");
    search=search.replace(/\\q/g,"\"");
    search=search.replace(/\\x80/g,"\\u20AC");
    search=search.replace(/\\x82/g,"\\u201A");
    search=search.replace(/\\x83/g,"\\u0192");
    search=search.replace(/\\x84/g,"\\u201E");
    search=search.replace(/\\x85/g,"\\u2026");
    search=search.replace(/\\x86/g,"\\u2020");
    search=search.replace(/\\x87/g,"\\u2021");
    search=search.replace(/\\x88/g,"\\u02C6");
    search=search.replace(/\\x89/g,"\\u2030");
    search=search.replace(/\\x8[aA]/g,"\\u0160");
    search=search.replace(/\\x8[bB]/g,"\\u2039");
    search=search.replace(/\\x8[cC]/g,"\\u0152");
    search=search.replace(/\\x8[eE]/g,"\\u017D");
    search=search.replace(/\\x91/g,"\\u2018");
    search=search.replace(/\\x92/g,"\\u2019");
    search=search.replace(/\\x93/g,"\\u201C");
    search=search.replace(/\\x94/g,"\\u201D");
    search=search.replace(/\\x95/g,"\\u2022");
    search=search.replace(/\\x96/g,"\\u2013");
    search=search.replace(/\\x97/g,"\\u2014");
    search=search.replace(/\\x98/g,"\\u02DC");
    search=search.replace(/\\x99/g,"\\u2122");
    search=search.replace(/\\x9[aA]/g,"\\u0161");
    search=search.replace(/\\x9[bB]/g,"\\u203A");
    search=search.replace(/\\x9[cC]/g,"\\u0153");
    search=search.replace(/\\x9[dD]/g,"\\u009D");
    search=search.replace(/\\x9[eE]/g,"\\u017E");
    search=search.replace(/\\x9[fF]/g,"\\u0178");
    if (options.indexOf("l")>=0) {
      search=search.replace(/\\b/g,"\b");
      search=search.replace(/\\f/g,"\f");
      search=search.replace(/\\n/g,"\n");
      search=search.replace(/\\r/g,"\r");
      search=search.replace(/\\t/g,"\t");
      search=search.replace(/\\v/g,"\v");
      search=search.replace(/\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}/g,
        function($0,$1,$2){
          return String.fromCharCode(parseInt("0x"+$0.substring(2)));
        }
      );
      search=search.replace(/\\B/g,"\\");
    } else search=search.replace(/\\B/g,"\\\\");
  }
  if (options.indexOf("l")>=0) {
    options=options.replace(/l/g,"");
    search=search.replace(/([.^$*+?()[{\\|])/g,"\\$1");
    if (!jexpr) replace=replace.replace(/\$/g,"$$$$");
  }
  if (options.indexOf("b")>=0) {
    options=options.replace(/b/g,"");
    search="^"+search
  }
  if (options.indexOf("e")>=0) {
    options=options.replace(/e/g,"");
    search=search+"$"
  }
  var search=new RegExp(search,options);
  var str1, str2;

  if (srcVar) {
    str1=env(args.Item(3));
    str2=str1.replace(search,jexpr?replFunc:replace);
    if (!alterations || str1!=str2) if (multi) {
      WScript.Stdout.Write(str2);
    } else {
      WScript.Stdout.WriteLine(str2);
    }
    if (str1!=str2) rtn=0;
  } else if (multi){
    var buf=1024;
    str1="";
    while (!WScript.StdIn.AtEndOfStream) {
      str1+=WScript.StdIn.Read(buf);
      buf*=2
    }
    str2=str1.replace(search,jexpr?replFunc:replace);
    WScript.Stdout.Write(str2);
    if (str1!=str2) rtn=0;
  } else {
    while (!WScript.StdIn.AtEndOfStream) {
      str1=WScript.StdIn.ReadLine();
      str2=str1.replace(search,jexpr?replFunc:replace);
      if (!alterations || str1!=str2) WScript.Stdout.WriteLine(str2);
      if (str1!=str2) rtn=0;
    }
  }
} catch(e) {
  WScript.Stderr.WriteLine("JScript runtime error: "+e.message);
  rtn=3;
}
WScript.Quit(rtn);

function replFunc($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) {
  var $=arguments;
  return(eval(replace));
}


تحديث مهم

لقد توقفت عن تطوير REPL.BAT، واستبدلته بـ JREPL.BAT.تحتوي هذه الأداة الأحدث على نفس وظائف REPL.BAT، بالإضافة إلى المزيد:

  • دعم Unicode UTF-16LE عبر إمكانات CSCRIPT unicode الأصلية وأي مجموعة أحرف أخرى (بما في ذلك UTF-8) عبر ADO.
  • القراءة مباشرة من/الكتابة مباشرة إلى ملف:لا حاجة لتوجيهات الإخراج، أو إعادة التوجيه، أو أمر النقل.
  • دمج JScript الذي قدمه المستخدم
  • وسيلة ترجمة مشابهة لـ unix tr، إلا أنها تدعم أيضًا البحث عن regex واستبدال JScript
  • تجاهل النص غير المطابق
  • بادئة خطوط الإخراج برقم السطر
  • و اكثر...

كما هو الحال دائمًا، يتم تضمين الوثائق الكاملة داخل البرنامج النصي.

أصبح الحل التافه الأصلي الآن أبسط:

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

الإصدار الحالي من JREPL.BAT متاح في DosTips.اقرأ جميع المشاركات اللاحقة في الموضوع لرؤية أمثلة الاستخدام وتاريخ التطوير.

استخدم FNR

استخدم ال fnr جدوى.لقد حصلت على بعض المزايا fart:

  • التعبيرات العادية
  • واجهة المستخدم الرسومية الاختيارية.يحتوي على "زر إنشاء سطر الأوامر" لإنشاء نص سطر الأوامر لوضعه في ملف دفعي.
  • أنماط متعددة الخطوط:تتيح لك واجهة المستخدم الرسومية العمل بسهولة مع أنماط متعددة الخطوط.في FART، سيتعين عليك الهروب يدويًا من فواصل الأسطر.
  • يسمح لك بتحديد ترميز الملف النصي.لديه أيضًا خيار الكشف التلقائي.

تحميل FNR هنا: http://findandreplace.io/?z=codeplex

مثال الاستخدام:fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"

لا أعتقد أن هناك طريقة للقيام بذلك باستخدام أي أوامر مضمنة.أقترح عليك تنزيل شيء مثل جنوين32 أو UnxUtils واستخدام sed الأمر (أو التنزيل فقط sed):

sed -c s/FOO/BAR/g filename

أعلم أنني تأخرت على الحفلة..

أنا شخصياً أحب الحل في:- http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

نستخدم أيضًا وظيفة Dedupe على نطاق واسع لمساعدتنا في تسليم ما يقرب من 500 رسالة بريد إلكتروني يوميًا عبر SMTP من:- https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o

وكلاهما يعمل بشكل أصلي دون الحاجة إلى أدوات أو أدوات مساعدة إضافية.

البديل:

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

DEDUPLICATOR (لاحظ استخدام -9 لرقم 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

شكرًا!

عندما تعمل مع جيت على ويندوز ثم أطلق النار ببساطة git-bash والاستخدام sed.أو، عند استخدام Windows 10، ابدأ تشغيل "Bash on Ubuntu on Windows" (من نظام Linux الفرعي) واستخدمه sed.

إنه محرر دفق، ولكن يمكنه تحرير الملفات مباشرةً باستخدام الأمر التالي:

sed -i -e 's/foo/bar/g' filename
  • -i يتم استخدام الخيار للتحرير في مكانه على اسم الملف.
  • -e يشير الخيار إلى أمر للتشغيل.
    • s يتم استخدامه لاستبدال التعبير الموجود "foo" بـ "bar" و g يتم استخدامه لاستبدال أي تطابقات تم العثور عليها.

ملاحظة بواسطة ereOn:

إذا كنت تريد استبدال سلسلة في الملفات ذات الإصدارات الخاصة بمستودع Git فقط، فقد ترغب في استخدام:

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

الذي يعمل العجائب.

لقد استخدمت بيرل، وهذا يعمل بشكل رائع.

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

.orig هو الامتداد الذي سيتم إلحاقه بالملف الأصلي

لعدد من الملفات المطابقة مثل *.html

for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x

لقد تلاعبت ببعض الإجابات الموجودة هنا وأفضّل الحل المحسّن ...

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

أو إذا كنت تريد حفظ الإخراج مرة أخرى إلى ملف ...

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

وتتمثل فائدة ذلك في أنه يمكنك توجيه الإخراج من أي برنامج.سوف ننظر في استخدام التعبيرات العادية مع هذا أيضا.لا يمكن معرفة كيفية تحويله إلى ملف BAT لتسهيل الاستخدام بالرغم من ذلك...:-(

مع ال استبدال.bat

1) مع e? الخيار الذي سيقيم تسلسلات الأحرف الخاصة مثل \n\r وتسلسلات يونيكود.في هذه الحالة سوف يحل محل المقتبسة "Foo" و "Bar":

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

2) استبدال مباشر حيث Foo و Bar لم يتم اقتباسها.

call replacer.bat "C:\content.txt" "Foo" "Bar"

إليك الحل الذي وجدته يعمل على نظام Win XP.في ملفي الدفعي الجاري تشغيله، قمت بتضمين ما يلي:

set value=new_value

:: Setup initial configuration
:: I use && as the delimiter in the file because it should not exist, thereby giving me the whole line
::
echo --> Setting configuration and properties.
for /f "tokens=* delims=&&" %%a in (config\config.txt) do ( 
  call replace.bat "%%a" _KEY_ %value% config\temp.txt 
)
del config\config.txt
rename config\temp.txt config.txt

ال replace.bat الملف على النحو التالي.لم أجد طريقة لتضمين هذه الوظيفة في نفس الملف الدفعي، لأن %%a يبدو أن المتغير دائمًا يعطي القيمة الأخيرة في الحلقة.

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

نلقي نظرة على هل هناك أي فائدة مثل sed لـ cmd.exe الذي طلب ما يعادله في نظام التشغيل Windows، يجب أن ينطبق على هذا السؤال أيضًا.ملخص تنفيذي:

  • ويمكن أن يتم ذلك في ملف دفعي، ولكنها ليست جميلة
  • الكثير من الملفات التنفيذية المتاحة لجهات خارجية والتي ستقوم بذلك نيابةً عنك، إذا كان لديك ترف التثبيت أو مجرد النسخ فوق ملف exe
  • يمكن إجراؤه باستخدام VBScript أو ما شابه إذا كنت بحاجة إلى شيء قادر على التشغيل على صندوق Windows دون تعديل وما إلى ذلك.

قد أتأخر قليلاً، ولكني أبحث كثيرًا عن أشياء مماثلة، حيث لا أريد أن أتحمل عناء الحصول على الموافقة على البرنامج.

ومع ذلك، عادةً ما تستخدم عبارة FOR بأشكال مختلفة.قام شخص ما بإنشاء ملف دفعي مفيد يقوم بالبحث والاستبدال.الق نظرة هنا.من المهم أن نفهم القيود المفروضة على الملف الدفعي المقدم.لهذا السبب لا أقوم بنسخ كود المصدر في هذه الإجابة.

اثنين من الملفات الدفعية التي توفر search and replace تمت كتابة الوظائف بواسطة أعضاء Stack Overflow dbenham و aacini استخدام native built-in jscript في ويندوز.

كلاهما robust و very swift with large files مقارنة بالبرمجة النصية الدفعية العادية، وأيضًا simpler لاستخدامها في الاستبدال الأساسي للنص.كلاهما لديه Windows regular expression نمط مطابقة.

  1. هذاsed-like يتم استدعاء الملف الدفعي المساعد repl.bat (بواسطة دبنهام).

    مثال باستخدام L التبديل الحرفي:

    echo This is FOO here|repl "FOO" "BAR" L
    echo and with a file:
    type "file.txt" |repl "FOO" "BAR" L >"newfile.txt"
    
  2. هذا grep-like يتم استدعاء الملف الدفعي المساعد findrepl.bat (بواسطة آسيني).

    مثال يحتوي على تعبيرات عادية نشطة:

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

كلاهما يصبح أدوات مساعدة قوية على مستوى النظام when placed in a folder that is on the path, أو يمكن استخدامه في نفس المجلد مع ملف دفعي، أو من موجه cmd.

كلاهما لديه case-insensitive مفاتيح وأيضا العديد من الوظائف الأخرى.

يعمل أمر Power Shell كالسحر

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

واجهت للتو مشكلة مماثلة - "البحث عن النص واستبداله داخل الملفات"، ولكن باستثناء أنه بالنسبة لأسماء الملفات والبحث/الاستبدال أحتاج إلى استخدام regex.لأنني لست على دراية بـ Powershell وأريد حفظ عمليات البحث لاستخدامها لاحقًا، فأنا بحاجة إلى شيء أكثر "سهل الاستخدام" (يفضل أن يكون به واجهة مستخدم رسومية).

لذلك، أثناء البحث في Google :) وجدت أداة رائعة - FAR (بحث واستبدال) (وليس ضرطة).

يحتوي هذا البرنامج الصغير على واجهة مستخدم رسومية جميلة ويدعم التعبير العادي للبحث في أسماء الملفات وداخل الملفات.العيب الوحيد هو أنه إذا كنت تريد حفظ إعداداتك، فيجب عليك تشغيل البرنامج كمسؤول (على الأقل على Win7).

هذا هو الشيء الوحيد الذي لا تعمل فيه البرمجة النصية المجمعة بشكل جيد.

النص morechilli سيعمل الرابط مع بعض الملفات، لكن لسوء الحظ سيختنق مع الملفات التي تحتوي على أحرف مثل الأنابيب وعلامات العطف.

يعد VBScript أداة مدمجة أفضل لهذه المهمة.انظر هذه المقالة على سبيل المثال:http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx

أعطت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%"

استخدم بوويرشيل في .bat - لنظام التشغيل Windows 7+

يعد تشفير utf8 اختياريًا، وهو جيد لمواقع الويب

@echo off
set ffile='myfile.txt'
set fold='FOO'
set fnew='BAR'
powershell -Command "(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8"

أنا أفضل استخدام sed من أدوات جنو لـ Win32, ، لا بد من ملاحظة ما يلي

  • اقتباس واحد '' لن تعمل في النوافذ، استخدم "" بدلاً من
  • sed -i لن يعمل على الويندوز، سوف يحتاج إلى ملف مبادلة

لذا فإن رمز العمل لـ sed للبحث عن النص واستبداله في ملف في Windows على النحو التالي

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

تحميل سيجوين (مجاني) واستخدم أوامر تشبه يونكس في سطر أوامر Windows.

أفضل رهان لك:سيد

يمكن أيضًا رؤية أدوات الاستبدال والاستبدال على https://zoomicon.github.io/tranXform/ (المصدر متضمن).والثاني هو مرشح.

الأداة التي تستبدل السلاسل في الملفات موجودة في VBScript (تحتاج إلى Windows Script Host [WSH] للتشغيل في إصدارات Windows القديمة)

ربما لا يعمل الفلتر مع Unicode إلا إذا قمت بإعادة الترجمة باستخدام أحدث إصدار من دلفي (أو باستخدام FreePascal/Lazarus)

لقد واجهت هذه المشكلة عدة مرات أثناء البرمجة ضمن Visual C++.إذا كان لديك، يمكنك استخدام Visual studio Find and Replace Utility.يسمح لك بتحديد مجلد واستبدال محتويات أي ملف في هذا المجلد بأي نص آخر تريده.

ضمن Visual Studio:تحرير -> ابحث واستبدالها في مربع الحوار المفتوح ، حدد المجلد الخاص بك واملأ "البحث عن" و "استبدال مع" مربعات ".نأمل أن تكون مفيدة.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top