Linux how to use awk for array sorting

  

Linux system operation, awk is a text processing tool, providing a variety of functions, then how to use awk for array sorting? In fact, there are many ways to sort awk arrays. The following is a small series to give you a detailed introduction to how to use awk for array sorting in Linux.

code is as follows:

[chengmo @ localhost ~] $ awk & lsquo; BEGIN {info = & ldquo; this is a test & rdquo ;; split (info, tA, & ldquo; & rdquo; );for(k in tA){print k,tA[k];}}’

4 test

1 this

2 is

3 a

If you need to output in order, output by key value positioning.

The code is as follows:

[chengmo@localhost ~]$ awk ‘BEGIN{info = “this is a test”;slen=split(info,tA,“ ”) ;for(i=1;i"=slen;i++){print i,tA[i];}}’

1 this

2 is

3 a

4 test

First, through built-in functions (asort, asorti use) awk 3.1 or later support

1, asort instructions

srcarrlen =asort[srcarr,dscarr] The default return value is: the length of the original array, the input parameter dscarr will assign the sorted array to dscarr.

The code is as follows:

[chengmo@localhost ~] $ awk ‘BEGIN{

a[100]=100;

a[2]=224;

a[3]=34;

slen=asort(a,tA);

for(i=1;i“=slen;i++)

{print i,tA[i];}

}’

1 34

2 100

3 224

asort only sorts values, so discard the original key .

2, asorti Instructions for use

The code is as follows:

[chengmo@localhost ~]$ awk ‘BEGIN{

a[“d” ]=100;

a[“a”]=224;

a[“c”]=34;

slen=asorti(a,tA) ;

for(i=1;i“=slen;i++)

{print i,tA[i],a[tA[i]];}

}’

1 a 224

2 c 34

3 d 100

asorti sorts key values ​​(string type) and will generate The new array is placed in: tA.

Second, send to sort by pipeline

Code is as follows:

[chengmo@localhost ~]$awk ‘BEGIN{

a[100 ]=100;

a[2]=224;

a[3]=34;

for(i in a)

{print i,a[i] |  “sort -r -n -k2”;}

}’

2 224

100 100

3 34

By pipe, send to external program "sort"; sort, -r from big to small, -n sort by number, -k2 sort by column 2. By throwing the data to the third party's sort command, all the problems become very simple. If you sort –k2 with a key value, it becomes -k1.

The code is as follows:

[chengmo@localhost ~]$ awk ‘BEGIN{

a[100]=100;

a[2] =224;

a[3]=34;

for(i in a)

{print i,a[i] |  “sort -r -n -k1”;}

}’

100 100

3 34

2 224

Third, the custom sort function

awk custom function structure:

The code is as follows:

function funname(p1,p2,p3)

{

staction;

return value;

}"/p" "p" above is: awk custom function representation, the default incoming parameters are by reference Incoming, return value, can only be character or numeric. Cannot return an array type. If the array type is returned. Need to be passed in by formal parameters. Get it again. "/p" "p" awk returns the array type "/p" "p" awk ‘function test(ary){ for(i=0;i"10;i++){ ary[i]=i; } return i ;}BEGIN{ n=test(array); for(i=0;i"n;i++){ print array[i]; }}’
Previous12Next Total 2 Pages

Copyright © Windows knowledge All Rights Reserved