Powershell 中 *Nix 'cut' 命令的等价物是什么? [英] What is an equivalent of *Nix 'cut' command in Powershell?

查看:35
本文介绍了Powershell 中 *Nix 'cut' 命令的等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在配置文件 (sample.cfg) 中有以下内容,

I have following content in a configuration file (sample.cfg),

Time_Zone_Variance(Mins):300
Alert_Interval(Mins):2
Server:10.0.0.9
Port:1840

我试图通过在 PowerShell 中使用 split: 之后存储每个值.但我无法产生需要的输出.

I'm trying to store an each values after the : by using split in PowerShell. but i'm not able to produce require output.

谁能告诉我如何使用 PowerShell split 解决上述问题?

Can someone tell me how to use PowerShell split for the above problem ?

推荐答案

你可以使用 Get-Content 读取文件的内容,然后通过 ForEach-Object,然后在每一行使用split命令,取数组中的第二项如下:

You can read the contents of the file using Get-Content, then pipe each line through ForEach-Object, then use the split command on each line, taking the second item in the array as follows:

$filename = "sample.cfg"

Get-Content $filename | ForEach-Object {
    $_.split(":")[1]
}

输出

300
2
10.0.0.9
1840

更新

我更喜欢@AnsgarWiechers 的方法,但是如果您真的需要特别命名的值,您可以创建一个哈希表并用值替换名称:

I prefer the approach by @AnsgarWiechers, but if you really need specifically named values you could create a hashtable and replace the name with the value:

$configValues = @{
    hour    = "Time_Zone_Variance(Mins)"
    min     = "Alert_Interval(Mins)"
    server  = "Server"
    port    = "Port"
}

Get-Content $filename | ForEach-Object {

    # Courtesy of Ansgar Wiechers
    $key, $value = $_ -split ':', 2

    foreach($configValuesKey in $($configValues.keys)) {
        if ($configValues[$configValuesKey] -eq $key)
        {
            $configValues[$configValuesKey] = $value
        }
    }
}

write-host "`nAll Values:"
$configValues
write-host "`nIndividual value:"
$configValues.port

输出

All Values:

Name                           Value                                                                                             
----                           -----                                                                                             
port                           1840                                                                                              
min                            2                                                                                                 
server                         10.0.0.9                                                                                          
hour                           300                                                                                               

Individual value:
1840

这篇关于Powershell 中 *Nix 'cut' 命令的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆