Powershell,如何从文件中获取所需的列

Powershell, how to get desired columns from a file

在windows powershell 中 输入文件数据

WL363998 google.com 172.217.166.46 32 7 WL363998 fb.com 157.240.16.35 32 7 WL363998 bing.com 13.107.21.200 32 6

我需要的输出文件

google.com 172.217.166.46 fb.com 157.240.16.35 bing.com 13.107.21.200

试试这个:

cat "Filepath" | %{$_.split("`t")[1,2] -join "`t"}

您可以尝试这样的操作:

(& {
    foreach ($line in Get-Content -Path .\data.txt)
    {
        $columns = $line -split '\s+'
        [PSCustomObject]@{
            Domain = $columns[1]
            IP = $columns[2]
        }
    } 
} | Out-String).Trim() | Out-File -FilePath output.txt -NoNewline

解释:

  • 将带有 Get-Content 的每一行读入一个字符串数组。
  • \s+ 在所有空格上拆分每一行。查看 about_split 了解更多信息。
  • 将第 1 列和第 2 列插入 PSCustomObject
  • 管道到 Out-String, so we can Trim() 尾随空格。
  • 通过管道传输到 Out-File 以创建一个新的输出文件,确保我们不包含带有 -NoNewline 的新行(可选)。

output.txt

Domain     IP
------     --
google.com 172.217.166.46
fb.com     157.240.16.35
bing.com   13.107.21.200