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,133
  • 25
  • 35
  • 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
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
  • 112,354
  • 20
  • 166
  • 226
2

If it is unix machine tac can be used.

Dinesh Reddy
  • 705
  • 8
  • 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
  • 39,326
  • 11
  • 49
  • 54
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
  • 71,025
  • 22
  • 98
  • 142