1

I'm having trouble trying to pipe a sort with a gawk. I currently have:

gawk -f p3a01.awk unsortedNames.txt | sort | gawk -f p3a01.awk

this is however giving me the wrong results. The gawk seems to work fine if I do something like:

gawk -f p3a01.awk unsortedNames.txt | sort > test1.out
gawk -f p3a01.awk test1.out

I'm not sure if there is a proper way to directly pipe sort to gawk. I would ideally like to do this all on one line

Snip of unsortedNames.txt:

Faye King
Lenny R Graph
I M Board
Grey White

p3a01.awk (prints last name first then rest of the name):

BEGIN{}
{
      printf $NF " ";
      $NF="";
      print $0;
}
END{}

p3a02.awk (prints the file in the original order after it has been ordered by last name):

BEGIN{}
{
     for(i=2;i<=NF;i++){
         printf $i " ";
     }
     print $1;
}
END{}

Final result (sorted by last name):

I M Board
Lenny R Graph
Faye King
Grey White
  • @SatōKatsura fixed. I've added my scripts. – below_avg_st Sep 28 '17 at 6:17
  • post how should look the expected result – RomanPerekhrest Sep 28 '17 at 6:19
  • What does not work? It works for me given the data that you present. Did you create these files on a Windows machine (this may create problems with carriage returns (DOS newlines)). Run the files through dos2unix. If that does not help, describe or show the wrong result. – Kusalananda Sep 28 '17 at 6:42
1

Optimized single-processed GNU Awk solution:

awk 'BEGIN{ PROCINFO["sorted_in"]="@ind_str_asc" }
     { a[$NF]=$0 }END{ for(i in a) print a[i] }' unsortedNames.txt


The output:

I M Board
Lenny R Graph
Faye King
Grey White
|improve this answer|||||
0

Your code seems to be working as advertised, so whatever errors you're experiencing may be related to invisible characters in the input data (\r at the end of lines?).

I noticed that you are removing the last field when you are transforming the data for sort. This is not necessary. You just need to prepend each line with the last field, and then remove it again after the sort:

$ awk '{ print $NF, $0 }' file | sort | cut -d ' ' -f 2-
I M Board
Lenny R Graph
Faye King
Grey White

The cut command will output all space-delimited fields from the second onwards.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.