I am looking to automate a task - which is updating an existing access control instruction of a server and making sure that the attributes defined in the instruction is in sorted order. The instructions will be of a specific syntax.
For example lets assume below listed is one of an existing instruction in a server. Attributes are the ones in between the (targetattr = "xx || yy")
In this existing instruction,
1) First, i want to sort the attributes defined in ascending order like
2) Then on the sorted instruction, I may want to add 1 or more strings like "gabcd" and "gbace" in between the existing strings (alphabetically ordered). So the expected final result must be something like below
awk FS='"' ' - invoke awk with double-quote as the field separator. { - for any line MYFS="||"; newlist=""; n=split($2,elements,MYFS); - Split field 2 into an array, using '||' to identify separate elements (and n assignment should be on split, not asort) asort(elements); - Sort the array for (i=1;i<n;i++) { newlist=newlist elements MYFS; } - loop around the (ordered) array to create a new string, appending the current element and '||' every time newlist=newlist elements[n]; - append the last element (should be n rather than i, or it will repeat the last-but-one) $2=newlist; - overwrite the value of field 2 with the list we just created print; - print the line
I believe that asort() is only available in gawk (GNU awk). Try executing
awk --version
which might give you the version. Assuming it's not gawk, then you could implement your own sort. Probably not as efficient as the built-in, but better than nothing. Example below using the original code from CarloM and adding a sort (bubble) function.
awk FS='"' '
# sort v1 into ascending order
# n = length(v1) rather than passing in the length isnt supported in all flavours of awk
function bubble( v1, n, s, i, pass, swap )
{
swap = 1;
pass = 0;
while( swap )
{
swap = 0;
pass++;
for( i = 0; i < n - pass; i++ )
{
if( v1 > v1[i+1] )
{
swap++;
s = v1;
v1 = v1[i+1];
v1[i+1] = s;
}
}
}
}
{
MYFS="||";
newlist="";
n=split($2,elements,MYFS);
bubble( elements, n ); for (i=1;i<n;i++) {
newlist=newlist elements MYFS;
}
newlist=newlist elements[n];
$2=newlist;
print;
}' inputfile
mine is NOT a gawk. so i tried running manual sorting code by copying it to a script. It throws out syntax errors while executing the script. i am not an shell expert and unable to fix the syntax errors of this code. did this code worked for you ? please help !
I cut/pasted the code from another post I made a while back on Unix.com while en route on a plane, so I didn't test it. There's a chance that I chopped something off, but after a quick peek at it again it looks OK to me. If you could post the errors, and your code, that might help determine what isn't working.
I'm again on a plane; I'm sure someone will see it and suggest changes/corrections.