简体   繁体   中英

How to replace string in files recursively

I'm developing one application. Some path have to be changed on the whole project. The path are fixed and the files can be edited (it is in ".cshtml" ).

So I think I can use a batch file to change all the " http://localhost.com " to " http://domain.com " for example (I know relative and absolute path, but here I HAVE to make that :-) )

So if you have code that can make that changes in files, it could be marvellous!

To complete my question, here it is the path of files and dir

MyApp
MyApp/Views
MyApp/Views/Index/page1.cshtml
MyApp/Views/Index/page2.cshtml
MyApp/Views/Another/page7.cshtml
...

Thanks to help me :-)

Something like this might work as well:

#!/bin/bash

s=http://localhost.com
r=http://example.com

cd /path/to/MyApp

grep -rl "$s" * | while read f; do
  sed -i "s|$s|$r|g" "$f"
done

Edit: Or not, since you just switched from to . A batch solution might look like this:

@echo off

setlocal EnableDelayedExpansion

for /r "C:\path\to\MyApp" %%f in (*.chtml) do (
  (for /f "tokens=*" %%l in (%%f) do (
    set "line=%%l"
    echo !line:
  )) >"%%~ff.new"
  del /q "%%~ff"
  ren "%%~ff.new" "%%~nxf"
)

Doing this in batch is really, really ugly, though (error-prone too), and you'd be far better off using sed for Windows , or (better yet) doing it in PowerShell:

$s = "http://localhost.com"
$r = "http://example.com"

Get-ChildItem "C:\path\to\MyApp" -Recurse -Filter *.chtml | ForEach-Object {
    (Get-Content $_.FullName) |
        ForEach-Object { $_ -replace [regex]::Escape($s), $r } |
        Set-Content $_.FullName
}

Note that -Filter only works in PowerShell v3. For earlier versions you have to do it like this:

Get-ChildItem "C:\path\to\MyApp" -Recurse | Where-Object {
    -not $_.PSIsContainer -and $_.Extension -eq ".chtml"
} | ForEach-Object {
    (Get-Content $_.FullName) |
        ForEach-Object { $_ -replace [regex]::Escape($s), $r } |
        Set-Content $_.FullName
}

You can do this:

find /MyApp -name "*.cshtml" -type f -exec sed -i 's#http://localhost.com#http://domain.com#g' {} +

Explanation

  • find /MyApp -name "*.cshtml" -type f looks for files with .cshtml extension in /MyApp structure.
  • sed -i 's/IN/OUT/g' replaces the text IN to OUT in the files.
  • hence, sed -i 's#http://localhost.com#http://domain.com#g' replaces http://localhost.com with http://domain.com .
  • exec .... {} + executes .... within the files found by find .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM