gpt4 book ai didi

windows - 如何递归替换文件中的字符串

转载 作者:可可西里 更新时间:2023-11-01 09:43:20 28 4
gpt4 key购买 nike

我正在开发一个应用程序。必须更改整个项目的某些路径。路径是固定的,文件可以编辑(在“.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
...

感谢帮助我:-)

最佳答案

类似这样的方法也可能有效:

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

关于windows - 如何递归替换文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17366786/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com