【问题标题】:Find the last three characters of a string with Powershell使用 Powershell 查找字符串的最后三个字符
【发布时间】:2020-10-22 13:46:55
【问题描述】:

我有一个文件列表,其中包含文件中的完整路径,并在 Powershell 的命令行上使用“Get-Content Filename”输出。我现在只想得到最后三个字符。子字符串似乎不可能。命令行上还有什么其他选项。

【问题讨论】:

  • 整个文件的最后三个字符?还是文件中每行的最后三个字符?
  • 对于任何字符串,您都可以使用$string -replace '.*(.{3})','$1'

标签: powershell


【解决方案1】:

你可以使用Substring(),你只需要手动计算起始索引:

$s = "abcdef"
if($s.Length -gt 3){
  $s.Substring($s.Length - 3) # returns "def"
} else {
  $s
}

您还可以使用-replace 正则表达式运算符删除最后三个字符之前的任何内容:

$s -replace '^.*(?=.{3}$)'

这里我们不需要长度检查,-replace 不会在模式不匹配任何内容时更改字符串。

-replace 也适用于可枚举输入,所以如果你想将操作应用于文件中的每一行,就这么简单:

(Get-Content $filename) -replace '^.*(?=.{3}$)'

replace 使用的模式描述:

^          # Match start of string
.*         # Match any number of any character
(?=.{3}$)  # Pattern MUST be followed by 3 characters and the end of the string

【讨论】:

  • 非常感谢,(Get-Content $filename) -replace '^.*(?=.{3}$)' 对我来说很好用。
猜你喜欢
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
  • 2023-03-20
  • 1970-01-01
  • 2017-05-24
  • 2014-10-04
  • 1970-01-01
相关资源
最近更新 更多