2

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 3

4

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=%s\n", $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
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.
2

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

  • -En - E 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.
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.