Search code examples
regexpowershellsubstringbacktrackingbackreference

PowerShell cut string in half


I have lines that consist of identical halves from which I want to remove one half; e.g, 'AbcAbc' should become 'Abc'.

The data always looks like:

10.22.20.106/tcp/8010.22.20.106/tcp/80
10.22.20.46/tcp/44310.22.20.46/tcp/443
10.22.20.90/tcp/44310.22.20.90/tcp/443
10.22.20.90/tcp/8010.22.20.90/tcp/80
10.22.20.89/tcp/44310.22.20.89/tcp/443
10.22.20.89/tcp/8010.22.20.89/tcp/80
10.22.20.29/tcp/44310.22.20.29/tcp/443
10.22.20.29/tcp/8010.22.20.29/tcp/80
10.22.20.122/tcp/44310.22.20.122/tcp/443
10.22.20.123/tcp/44310.22.20.123/tcp/443
10.22.20.79/tcp/44310.22.20.79/tcp/443
10.22.20.79/tcp/8010.22.20.79/tcp/80
10.22.20.78/tcp/44310.22.20.78/tcp/443
10.22.20.78/tcp/8010.22.20.78/tcp/80
10.22.20.74/tcp/44310.22.20.74/tcp/443
10.22.20.74/tcp/8010.22.20.74/tcp/80
10.22.20.22/tcp/44310.22.20.22/tcp/443
10.22.20.22/tcp/8010.22.20.22/tcp/80
10.22.20.99/tcp/44310.22.20.99/tcp/443
10.22.20.99/tcp/8010.22.20.99/tcp/80
10.22.20.54/tcp/44310.22.20.54/tcp/443
10.22.20.54/tcp/8010.22.20.54/tcp/80

I count the number of characters in the string and then halve it, but not sure how to use the calculated (halved) number of characters to cut the original string.

$vip_ip = $vip_line.("Virtual IP Address/Protocol/Port")
$half_string = $vip_ip.length /2

$vip_ip.length 44

$half_string 22

$vip_cut = $vip_ip.(0,-$halfstring)

Solution

  • You are trying to gather the information that you would need for the string method "".SubString()

    In your case you just need something like this:

    $vip_ip.substring(0,$halfstring)
    

    From the start of the string and go halfway. Could also start from halfway to the end as well since the answer is the same. SubString() supports both overloads.

    $vip_ip.substring($halfstring)