Home > Enterprise >  bash how to print list of devices In continuous order
bash how to print list of devices In continuous order

Time:03-15

the file - list_of_disk_devices.txt , contain list of disk devices

the problem with file - list_of_disk_devices.txt , is that list of devices isn't sorted with the right order

actually we need to print the order as the following:

sdb
.
.
sdz
sdaa
.
.
.
sdaz
sdba
.
.
.
sdbz

and file looks like:

more list_of_disk_devices.txt

sdau
sdav
sdaw
sdax
sday
sdaz
.
.
.
sdp
sdq
sdr
sds
sdz
sdaa
sdab
sdac
sdad
sdae
sdaf
sdag
.
.
.
sdba
sdam
sdbb
sdan
sdbc
sdao
sdat
sdau
sdav
sdd
sde
sdf
sdg
sdk
sdl
.
.
.
sds
sdt
sdu
sdv
sdw
sdx
sdy
sdz
sdaa
sdab
sdac
sdad
sdae
sdaf
.
.
.
sdak
sdal
sdba
sdbe
sdap
sdbh
sdas
sdat

we also tried with sort command with many options but without success

CodePudding user response:

cat list_of_disk_devices.txt  | awk '{print length($1),$1}' |sort | awk '{print $NF}'

output:

sda
sdb
sdc
sdd
sde
sdf
sdg
sdh
sdi
sdj
sdk
sdl
sdm
sdn
sdo
sdp
sdq
sdr
sds
sdt
sdu
sdv
sdw
sdx
sdy
sdz
sdaa
sdab
sdac
sdad
sdae
sdaf
sdag
sdah
sdai
sdaj
sdak
sdal
sdam
sdan
sdao
sdap
sdaq
sdar
sdas
sdat
sdau
sdav
sdaw
sdax
sday
sdaz
sdba
sdbb
sdbc
sdbd
sdbe
sdbf
sdbg
sdbh

CodePudding user response:

Using gawk you can specify the sort order of the array via a user defined function.

gawk '
    function my_comp(i1, v1, i2, v2) {
        if (length(v1) > length(v2)) {
            return 1;
        }
        if (length(v1) == length(v2)) {
            return (v1 >= v2);
        }
        return -1;
    }

    {
        a[NR] = $1;
    }

    END {
        PROCINFO["sorted_in"] = "my_comp";
        for (k in a) {
            print a[k];
        }
    }
' list_of_disk_devices.txt

CodePudding user response:

cat list_of_disk_devices.txt | sort or just sort list_of_disk_devices.txt

  • Related