Grekton
Grekton

Reputation: 43

IPV6 address shortening in shell and powershell

I have to make a script in shell and PowerShell that shortens ipv6 addresses as much as possible.

Like:

Input: 2001:0db8:03cd:0000:0000:ef45:0006:0123
Output: 2001:db8:3cd:::ef45:6:123

And the script should give a description of itself if -help parameter used but i dont know how to do that in PowerShell.

This is my code in PowerShell, it shortens the addresses correctly:

    param([parameter(Mandatory=$true)]$file)

if (test-path $file){
    foreach ($ip in Get-Content $file){
        $ip=$ip.Replace("0000","")
        Write-Host $ip

}
}

I have no idea how to do the shortening in shell, I tried like this but didn't work:

#!/bin/sh

if [ $1 = "-help" ]
then
echo description

else file = $1
fi

for ip in `cat ipv6.txt`
do
    $ip=$line
    $replace=""
    $echo ${var//0000/$replace}
done

This is the txt file with the addresses: http://uptobox.com/6woujdvdfkmh

Upvotes: 3

Views: 1135

Answers (3)

Andi-OTC
Andi-OTC

Reputation: 91

$longIPAddress = '2001:0db8:03cd:0000:0000:ef45:0006:0123'
$shortIPAddress = ([IPAddress]$longIPAddress).IPAddressToString
$shortIPAddress
2001:db8:3cd::ef45:6:123

Upvotes: 1

Pete
Pete

Reputation: 26

We might be going to the same school. This is what I was told to do and it works perfectly:

cat filename | sed -e 's/:0*/:/g' filename

Upvotes: 1

Keith Hill
Keith Hill

Reputation: 201662

The beauty of PowerShell is that you have access to a rich library that has methods for doing this for you. Try this:

<#
.SYNOPSIS
    Converts long form IP address into its short form
.DESCRIPTION
    Converts long form IP address into its short form
.PARAMETER IPAddress
    The IP address to convert.
.EXAMPLE
    PS C:\> ConvertTo-IPAddressCompressedForm 2001:0db8:03cd:0000:0000:ef45:0006:0123
#>
function ConvertTo-IPAddressCompressedForm($IPAddress) {
     [System.Net.IPAddress]::Parse($IPAddress).IPAddressToString
}

C:\> ConvertTo-IPAddressCompressedForm 2001:0db8:03cd:0000:0000:ef45:0006:0123
2001:db8:3cd::ef45:6:123

Note that to get usage in PowerShell based on the doc comments use:

ConvertTo-IPAddressCompressedForm -?

Upvotes: 3

Related Questions