【问题标题】:Remove a substring from a filename with Powershell使用 Powershell 从文件名中删除子字符串
【发布时间】:2013-05-03 12:35:51
【问题描述】:

在部署场景中,我需要重命名配置文件。每个环境(Dev.Test、Dev.Prod、Integration、Prod)都有配置文件。例如,如果 web.config 用于 Dev.Test 环境,它将被称为 web.Dev.Test.config。在目标机器上,我需要使用 Powershell 将文件重命名为原始名称(即从 web.Dev.Test.config 到 web.config)。

$test = "web.Dev.Prod.config"
$environment = $test | Select-String -Pattern ".*\.(?<environment>(Dev.Test|Dev.Prod|Prod|Integration))\.config" | select -expand Matches | foreach {$_.groups["environment"].value} 
if ($test -match "Dev.Prod")
{
  $environment = "Dev.Prod"
}
$environment
$newFileName = $test.Remove($test.IndexOf($environment),$environment.Length + 1)
$newFileName

我遇到的问题是,Regex 没有找到 Dev.Prod 环境,而是返回 Prod。这就是我引入 if 语句的原因。我想知道是否有更优雅的方式使用 Powershell 重命名文件。

【问题讨论】:

    标签: regex powershell rename


    【解决方案1】:

    注意贪婪匹配。修改以".*\.(?" 开头的正则表达式为".*?\.(?"

    【讨论】:

      猜你喜欢
      • 2015-01-11
      • 2014-09-14
      • 2015-05-18
      • 1970-01-01
      • 2016-10-18
      • 2017-04-01
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多