字符串操作 - Powershell

String manipulation - Powershell

我有一个名为 notification.txt 的文件,其中包含我需要 trim 并将 trimmed 输出传递给另一个命令的数据。

文件是随机行数,可以是 1 行,也可以是 100+ 行,它们看起来像这样:

hostname.domain.xyz                      Notification
hostname.domain.xyz                      Notification
hostname.domain.xyz                      Notification
hostname.domain.xyz                      Notification

我正在寻找 trim 从第一个 . 到右边的所有内容,它只会给我留下一个 array/variable 中的主机名,然后我可以用它来传递到另一个命令。

您可以通过调用 Split 并丢弃除第一部分以外的所有内容来删除第一次出现 . 后的所有内容:

$strings = @(
  'host1.domain.tld       Notification'
  'host2.domain.tld       Notification'
  'host3.domain.tld       Notification'
  'host4.domain.tld       Notification'
  'host5.domain.tld       Notification'
)

$hostnames = $strings |ForEach-Object { $_.Split('.')[0] }

$_.Split('.') returns 一个字符串数组(例如 @('host1','domain','tld Notification')),[0] 给出了数组中的第一个元素


或者,使用 -replace 正则表达式运算符:

$hostnames = $strings -replace '\..*$'

正则表达式模式 \..*$ 将匹配第一个文字点 . 和它之后的所有内容,直到字符串结束,并且因为我们使用的是 -replace 运算符没有将字符串替换为第二个参数,整个部分将被删除。