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])}'
如果是unix,则可以使用tac
。
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).
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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.