【问题标题】:Powershell search and replace part of a stringPowershell搜索和替换字符串的一部分
【发布时间】:2016-01-19 10:02:26
【问题描述】:

我有一个包含以下内容的文件:

123
456
789
XYZ
ABC999XXXXXXX

我需要在文件中搜索 3 个数字字符,并根据用户输入替换第一个和第三个字符。如果用户输入字符 1 = 0 和字符 3 = 9,我需要返回。

029
059
089

我试图通过简单的搜索和替换来做到这一点,而不是为每个字符创建一个变量。另外值得注意的是,我需要搜索 3 个数字的条件,丢弃字母字符行。

请注意:这是我需要做的简化版本。情况很长,还有更多的领域,但我希望将其归结为我可以使用的东西。提前致谢。

【问题讨论】:

  • -replace'^\d(\d)\d$','0${1}9'
  • 如果用户选择1=0,需要把4变成0,7变成0吗?
  • 你能给我们看一个你尝试过的样本吗? PetSerAl 为您提供所需的大部分内容。
  • @TessellatingHeckler - 我认为用户输入的意思是“使所有第一个字符为 0,所有第三个字符为 9。至少这是示例支持的解释。
  • @EBGreen 哦当然,1和3分别表示第一个和第三个字符;我搞混了,因为第一行有 1 和 3 这些位置。

标签: powershell search replace


【解决方案1】:

假设条件如您所述,评论中建议的-replace 操作应该可以满足您的需求。

您需要做的就是获取用户输入并将其插入到替换字符串中,示例如下:

# Get user input for the first digit
do{
    $a = Read-Host -Prompt "Input 1st digit"
} while ($a -notmatch "^\d$")

# Get user input for the third digit    
do{
    $b = Read-Host -Prompt "Input 3rd digit"
} while ($b -notmatch "^\d$")

# pattern that matches exactly 3 digits, captures the middle one
$pattern = "^\d(\d)\d$"

# replacement consisting of the user input and a reference to the capture group
$replace = "$a{0}$b" -f '${1}'

# Let's replace!
$InputObject = Get-Content "C:\my\file\path.txt"    
$InputObject -replace $pattern,$replace

【讨论】:

    猜你喜欢
    • 2015-11-13
    • 2015-05-02
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    相关资源
    最近更新 更多