Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

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
share|improve this answer
add comment
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
share|improve this answer
    
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
add comment
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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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