【问题标题】:How to replace string in files recursively如何递归替换文件中的字符串
【发布时间】:2013-06-28 14:16:51
【问题描述】:

我正在开发一个应用程序。必须在整个项目中更改某些路径。路径是固定的,可以编辑文件(在 ".cshtml" 中)。

所以我想我可以使用批处理文件将所有“http://localhost.com”更改为“http://domain.com”(我知道相对路径和绝对路径,但在这里我必须这样做:-))

因此,如果您有可以在文件中进行更改的代码,那就太棒了!

为了完成我的问题,这里是文件和目录的路径

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

感谢帮助我:-)

【问题讨论】:

  • 如果你说it would be marvellous,我们会帮你的,但是,唉,你说it could be marvellous

标签: windows batch-file command-line-interface


【解决方案1】:

类似的方法也可以:

#!/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

编辑: 或者没有,因为您刚刚从 切换到。批处理解决方案可能如下所示:

@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"
)

批量执行此操作确实,确实丑陋,但(也容易出错),您最好使用 sed for Windows,或者(更好)在 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
}

请注意,-Filter 仅适用于 PowerShell v3。对于早期版本,您必须这样做:

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
}

【讨论】:

  • 为什么会这样?您的问题是关于 bash,而不是关于批处理文件。
  • @clement 使用批处理和 PowerShell 解决方案更新了答案。不过,真的不建议为此使用批处理。
【解决方案2】:

你可以这样做:

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

说明

  • find /MyApp -name "*.cshtml" -type f/MyApp 结构中查找扩展名为 .cshtml 的文件。
  • sed -i 's/IN/OUT/g' 将文件中的文本 IN 替换为 OUT。
  • 因此,sed -i 's#http://localhost.com#http://domain.com#g'http://localhost.com 替换为 http://domain.com
  • exec .... {} +find 找到的文件中执行 ....。

【讨论】:

  • OP 实际上可能希望您将 INOUT 替换为实际值。
  • +1。我可以使用+ 而不是\;。它的行为类似于xargs,因此将执行较少的“sed”调用。
  • @devnull 感谢您的编辑,虽然我刚刚完成。我回滚你的版本!
  • 我不知道,@TrueY。我刚刚用time 对其进行了测试,您的选择花了一半的时间。谢谢!
  • @fedorqui:不客气!不错的解决方案!无论如何option 不是我的...它属于find。 ;)
猜你喜欢
  • 2023-03-04
  • 2018-12-29
  • 2017-04-24
  • 2017-08-25
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 2013-08-21
相关资源
最近更新 更多