Kawaljeet Singh
Kawaljeet Singh

Reputation: 63

Powershell, how to get desired columns from a file

In windows powershell Input file data

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

Outfile which i needed

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

Upvotes: 1

Views: 122

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

You could try something like this:

(& {
    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

Explanation:

  • Read each line with Get-Content into an array of strings.
  • Split each line on all whitespace with \s+. Have a look at about_split for more information.
  • Insert 1st and 2nd columns into PSCustomObject.
  • Pipe to Out-String, so we can Trim() trailing whitespace.
  • Pipe to Out-File to create a new output file, making sure we don't include new lines with -NoNewline(optional).

output.txt

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

Upvotes: 1

wasif
wasif

Reputation: 15470

Try this:

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

Upvotes: 0

Related Questions