title: Extract IPv4 and IPv6 Address Ranges in Bash?
body: <p>I'm writing a bash script in which I need to extract IPv4 and IPv6 Address Ranges from multiple strings and then format it as per the requirements before saving to the file.</p>
  
  <p>I've got the regex working fine: <a href="http://regexr.com?38jsb" rel="nofollow">http://regexr.com?38jsb</a> (Not optimized, roughly added)</p>
  
  <p>However, with bash it throws an error if i use with <code>egrep</code> which states <code>egrep: repetition-operator operand invalid</code></p>
  
  <p>Here's my bash script:</p>
  
  <pre><code>#!/bin/bash
  
  regex="(?&gt;(?&gt;([a-f\d]{1,4})(?&gt;:(?1)){3}|(?!(?:.*[a-f\d](?&gt;:|$)){})((?1)(?&gt;:(?1)){0,6})?::(?2)?)|(?&gt;(?&gt;(?1)(?&gt;:(?1)){5}:|(?!(?:.*[a-f\d]:){6,})(?3)?::(?&gt;((?1)(?&gt;:(?1)){0,4}):)?)?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?&gt;\.(?4)){3}))\/\d{1,2}"
  
  echo "v=abc ip4:127.0.0.1/19 ip4:192.168.1.1/32 ip4:192.168.2.50/20 ip6:2001:4860:4000::/36 ip6:2404:6800:4000::/36 ip6:2607:f8b0:4000::/36 ip6:2800:3f0:4000::/36 ip6:2a00:1450:4000::/36 ip6:2c0f:fb50:4000::/36 ~all" | egrep -o $regex
  </code></pre>
  
  <p>How can i extract both type of IP ranges in bash? What's a better solution?</p>
  
  <p><strong>Note:</strong> I'm using sample data for testing purpose</p>