skip to Main Content

I have a file iplist.txt with contents:

1.2.3.4
127.0.0.1
192.168.1.0/24
1111:2222:3333:4444::
5.6.7.8

im trying to find a way out to export a new file WITHOUT IPv6 and with prefix on every line something like that:

exportediplist.txt

/ip add address=1.2.3.4
/ip add address=127.0.0.1
/ip add address=192.168.1.0/24
/ip add address=5.6.7.8

the first thing i`ve tryied to do is to add a prefix with:

originalfile=/somepath/iplist.txt
exportedfile=/somepath/exportediplist.txt
sed -e 's#^#/ip add address=#' $originalfile > $exportedfile

and it works ok but i cant figure out how to remove IPv6 from file. Its not important to use sed, just anything that works with debian.

3

Answers


  1. With GNU sed, you can use

    sed -En '/([0-9]+.){3}[0-9]+/{s,,/ip add address=&,p}' $originalfile > $exportedfile
    

    Or, a bit more precise expression to match entire IPv4-like lines:

    sed -En '/^([0-9]+.){3}[0-9]+(/[0-9]+)?$/{s,,/ip add address=&,p}' $originalfile > $exportedfile
    

    See sed online demo #1 and demo #2.

    Details

    • -EnE enables POSIX ERE syntax and n suppresses default line output
    • /([0-9]+.){3}[0-9]+/ – finds all lines with dot-separated 4 numbers
    • /^([0-9]+.){3}[0-9]+(/[0-9]+)?$/ is the same, but additionally checks for start of string (^) and end of string ($) and also matches an optional port number after / with (/[0-9]+)?
    • s,,/ip add address=&, – on the lines found, replaces the match with /ip add address= + match value
    • p – prints the outcome.
    Login or Signup to reply.
  2. A grep/sed combo:

    $ egrep -v ':' iplist.txt | sed 's|^|/ip add address=|g'
    /ip add address=1.2.3.4
    /ip add address=127.0.0.1
    /ip add address=192.168.1.0/24
    /ip add address=5.6.7.8
    

    Another idea using just sed:

    $ sed '/:/d;s|^|/ip add address=|g' iplist.txt
    /ip add address=1.2.3.4
    /ip add address=127.0.0.1
    /ip add address=192.168.1.0/24
    /ip add address=5.6.7.8
    

    Where:

    • /:/d – skips/deletes any line containing a colon (:)
    • s|^|ip add address'|g – prefaces the remaining lines with the desired string

    One awk idea:

    $ awk '/:/ { next } { printf "/ip add address=%sn", $0}' iplist.txt
    /ip add address=1.2.3.4
    /ip add address=127.0.0.1
    /ip add address=192.168.1.0/24
    /ip add address=5.6.7.8
    
    Login or Signup to reply.
  3. A very simple one-liner awk:

     awk '!/:/{print "/ip add address="$0}' infile >outfile
    

    How it works:

    • !/:/: If it contains no colon character, select line for processing.
    • {print "/ip add address="$0}: Process line by adding the new prefix stuffs.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search