code_junkie

How can you find and replace text in a file using the Windows command-line environment?

Nov 10th, 2011
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. Get-Content test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
  2.  
  3. fart.exe -p -r -c -- C:toolsperl-5.8.9* @@APP_DIR@@ C:tools
  4.  
  5. sed -c s/FOO/BAR/g filename
  6.  
  7. set str=teh cat in teh hat
  8. echo.%str%
  9. set str=%str:teh=the%
  10. echo.%str%
  11.  
  12. teh cat in teh hat
  13. the cat in the hat
  14.  
  15. set value=new_value
  16.  
  17. :: Setup initial configuration
  18. :: I use && as the delimiter in the file because it should not exist, thereby giving me the whole line
  19. ::
  20. echo --> Setting configuration and properties.
  21. for /f "tokens=* delims=&&" %%a in (configconfig.txt) do (
  22. call replace.bat "%%a" _KEY_ %value% configtemp.txt
  23. )
  24. del configconfig.txt
  25. rename configtemp.txt config.txt
  26.  
  27. @echo off
  28.  
  29. :: This ensures the parameters are resolved prior to the internal variable
  30. ::
  31. SetLocal EnableDelayedExpansion
  32.  
  33. :: Replaces Key Variables
  34. ::
  35. :: Parameters:
  36. :: %1 = Line to search for replacement
  37. :: %2 = Key to replace
  38. :: %3 = Value to replace key with
  39. :: %4 = File in which to write the replacement
  40. ::
  41.  
  42. :: Read in line without the surrounding double quotes (use ~)
  43. ::
  44. set line=%~1
  45.  
  46. :: Write line to specified file, replacing key (%2) with value (%3)
  47. ::
  48. echo !line:%2=%3! >> %4
  49.  
  50. :: Restore delayed expansion
  51. ::
  52. EndLocal
  53.  
  54. Const ForReading = 1
  55. Const ForWriting = 2
  56.  
  57. strFileName = Wscript.Arguments(0)
  58. strOldText = Wscript.Arguments(1)
  59. strNewText = Wscript.Arguments(2)
  60.  
  61. Set objFSO = CreateObject("Scripting.FileSystemObject")
  62. Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
  63. strText = objFile.ReadAll
  64. objFile.Close
  65.  
  66. strNewText = Replace(strText, strOldText, strNewText)
  67. Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
  68. objFile.WriteLine strNewText
  69. objFile.Close
  70.  
  71. perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" <fileName>
  72.  
  73. for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x
Add Comment
Please, Sign In to add comment