使用powershell删除单词的第一个和最后三个字符

时间:2015-07-13 19:20:23

标签: powershell

我在文本文件中有一个用户列表,其名称格式如下: xn-tsai-01。

如何编写脚本以删除 xn- KEEP THIS -01 ,以便输出如下: tsai

我知道如何在bash中执行此操作,但对PowerShell不太熟悉。

提前致谢!

4 个答案:

答案 0 :(得分:4)

Why not use Substring method. If you will always trim the first three characters, you can do the following assuming the variable is a string type.

$string = xn-tsai-01
$string.Substring(3)

答案 1 :(得分:3)

以下是使用正则表达式快速完成此操作的方法:

'xn-tsai-01' -replace '.*?-(.*)-.*','$1'

列表示例:

(Get-Content list.txt) -Replace '.*?-(.*)-.*','$1'

答案 2 :(得分:1)

Boe的例子可能是效率最高的。

另一种方法是使用split()方法,如果它们采用统一格式。

Get-Content .\list.txt | % { ($_.Split('-'))[1] }

%是ForEach

的别名

答案 3 :(得分:0)

您可以使用.NET字符串方法IndexOf("-")查找第一个,LastIndexOf("-")查找字符串中最后一次出现的“ - ”。

将这些索引与Substring()一起使用以删除不必要的部分:

function Clean-Username {
    param($Name)
    $FirstDash = $Name.IndexOf("-") + 1
    $LastDash  = $Name.LastIndexOf("-")
    return $Name.Substring( $f, $l - $f )
}

PS C:\> Clean-UserName -Name "xn-tsai-01"
tsai