2

Hey everyone I am making an awk bash script that will take an input text file such as:

1111 Joe Brown
2222 Charlie Rogers
3333 Chris Williams
4444 Rob Black

And simply reverse the order of the rows, so output would be:

4444 Rob Black
3333 Chris Williams
2222 Charlie Rogers
1111 Joe Brown

I am getting a syntax error saying that there is an error near "(" and also that I have an extra "{" I cannot figure out what is happening here is my code:

#!/bin/bash
awk '{a[NR]=$0} END (for(i=NR; i>=1; i--)) printf("%s\n",a[i])}'
qorz
  • 49
  • 1
  • 7

5 Answers5

5

You can probably use just sort(1) command.

sort -nr < input.txt

Sort simply takes the input file and tries to sort it, taking the whitespace as a separator (which is our case), so it sorts the input by first column. If you need non-alphabetical sorting of the first column, the -n switch is needed (to sort numerically). The -r switch just reverses the output (ascending/descending).

tvm
  • 3,263
  • 27
  • 37
  • If you simply need to reverse the content of the file, you can use tac(1), which is present on the most unix systems, as @Dinesh mentioned. – tvm Mar 11 '14 at 14:44
  • I m trying to use this -r to reverse my sort. I am trying to sort by two columns simultaneously, ie names and logintime. i want to sort names in alphabetical order, but login time is to be latest login time first. using -r reverses both the sorts for each column. – Tan Yu Hau Sean Jul 31 '22 at 05:29
4

You have two extra brackets there. Correcting it:

awk '{a[NR]=$0} END {for(i=NR; i>=1; i--) printf("%s\n",a[i]);}' file

If you don't have to use awk, you can do easily with: tac file

P.P
  • 117,907
  • 20
  • 175
  • 238
2

If it is unix machine tac can be used.

Dinesh Reddy
  • 775
  • 1
  • 11
  • 25
2

Here is an awk variation:

awk '{a[i++]=$0} END {while(i--) print a[i]}' file
4444 Rob Black
3333 Chris Williams
2222 Charlie Rogers
1111 Joe Brown
Jotne
  • 40,548
  • 12
  • 51
  • 55
0

perl solution:

$ perl -e 'print reverse <>' file
4444 Rob Black
3333 Chris Williams
2222 Charlie Rogers
1111 Joe Brown

or sed

$ sed '1!G;h;$!d' file
4444 Rob Black
3333 Chris Williams
2222 Charlie Rogers
1111 Joe Brown
jaypal singh
  • 74,723
  • 23
  • 102
  • 147