0

in my ksh script I need to add the following task ( OS - linux/solaris )

I have the following file

 more test.txt


 /etc/backup/app 172.1.120      172.110.120 
 /etc/backup/app 172.1.120.12   172.110.120.98 
 /etc/backup/app 192.1.120      192.120.120 
 /etc/backup/app 172.1.120.1      172.110.120.7 
 /var/log/df     193.23.2       193.23.2
 /var/log/df     193.23.2.111   193.23.2.159

how to locate all IP's with 4 octets in the beginning of the file , and then the others IP's with 3 octets

Remark – sort IP's will be according to the second field

Example of requested file ( after sort )

    more test.txt

    /etc/backup/app 172.1.120.12   172.110.120.98 
    /etc/backup/app 172.1.120.1    172.110.120.7
    /var/log/df     193.23.2.111   193.23.2.159
    /etc/backup/app 172.1.120      172.110.120 
    /etc/backup/app 192.1.120      192.120.120 
    /var/log/df     193.23.2       193.23.2

Solution can be done with sort or ksh/awk/sed/perl one liner ...etc

2

Provided you have GNU awk here is the one-liner you need:

$ awk '{n=split($2,ip,".");if(n==4)print $0;else a[$2]=$0}END{n=asorti(a,b);for(i=1;i<=n;i++)print a[b[i]]}' file
/etc/backup/app 172.1.120.12   172.110.120.98 
/etc/backup/app 172.1.120.1    172.110.120.7 
/var/log/df     193.23.2.111   193.23.2.159
/etc/backup/app 172.1.120      172.110.120 
/etc/backup/app 192.1.120      192.120.120 
/var/log/df     193.23.2       193.23.2
0
awk '{printf "%s.,%s\n", $2, $0}' | \
sed -E -e 's/^(([0-9]+\.){4}),/0.\1,/' -e 's/^(([0-9]+\.){3}),/1.\1,/' | \
sort -t. -k 1,1 -k 3,3 | \
sed -E -e 's/^[^,]+,//'`

The idea is to:

  1. Copy relevant field to beginning of each line and add special separator (comma in this case)
  2. Use sed to prepend some value that depends on number of octets in IP address (I used 0 for 4 octets and 1 for 3 octets)
  3. Sort the values on relevant fields
  4. Strip out everything we added
  • the problem is that sed -E isnt illegal option on Solaris , is it possible to find other flag to support both OS ( Linux and Solaris ) ? – yael Apr 8 '13 at 14:28
0
cat <(awk '{if($2~/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/){print $0}}' test.txt | sort -k 2) <(awk '{if($2~/^[0-9]*\.[0-9]*\.[0-9]*$/){print $0}}' test.txt | sort -k 2)
  • Match lines where the second field has 4 octets and sort
  • Match lines where the second field ends after 3 octets and sort
  • Concatenate the two results together

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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