Sort file based on number of delimeters in line

Hi,

Need to sort file based on the number of delimeters in the lines.

cat testfile
/home/oracle/testdb
/home
/home/oracle/testdb/newdb
/home/oracle

Here delimeter is "/"

expected Output:

/home/oracle/testdb/newdb
/home/oracle/testdb
/home/oracle
/home

TIA

Try

 awk -F\/ '{print NF, $0}' file | sort -nr | awk 'sub ($1 FS, _)'
/home/oracle/testdb/newdb
/home/oracle/testdb
/home/oracle
/home

Hello Sumanthsv,

Could you please try following and let me know if this helps.

awk '{A=$0;count=gsub(/\//,X,A);array[count]=array[count]?array[count] ORS $0:$0;} END{for(j=NR;j>=1;j--){if(array[j]){print array[j]}}}'  Input_file

Output will be as follows.

/home/oracle/testdb/newdb
/home/oracle/testdb
/home/oracle
/home

EDIT: Adding a non-one liner form for same solution.

awk '{
        A=$0;
        count=gsub(/\//,X,A);
        array[count]=array[count]?array[count] ORS $0:$0;
     }
        END{
                for(j=NR;j>=1;j--){
                                        if(array[j]){
                                                        print array[j]
                                                    }
           }
     }
    '   Input_file
 

Thanks,
R. Singh

If all that you need is to have the pathnames of the files in a directory to sort before the pathname of the directory itself, all you need is:

sort -r testfile