I am trying to sort a variable number of columns of text, sometimes there are 3 fields sometimes there are 2.
Example input:
George W. Bush
Brack Obama
Micky Mouse
John F. Kennedy
Desired result:
George W. Bush
John F. Kennedy
Micky Mouse
Brack Obama
I want to get them in alphabetical order by last name, so using the $3
or $2
field.
So far, I've flipped each line to have the last name in front. However, to sort them I can't seem to flip them back. Ive tried arrays and I get loads more output then expected(repeated).
I'd like to keep this only as a awk file.
I've thought about using another awk file to flip them back in (let's say) a script of awk files, but I am not able to create a file while in awk (using bash scripts). I've been reading A Practical Guide to Linux but the examples I've seen seem all the same. Thanks for reviewing my question.
Currently this is how I am getting it done
{
#print $3 " " $1 " " $2;
if($3 == ""){
#print "me";
print $2 " " $1;
#list[$3]= $2" "$1
}else{
print $3" "$1" "$2 ;
#list[$3]= $3" " $2" "$1;}
#for(result in list){ print list[result]; }
}
}
gawk -f fileUsed alphRecoredToBeUsed | sort
Leaves me with ranged values that get sorted the way I want them. However presenting them with the 1st original value while keeping the alpha ordering.