简体   繁体   English

Bash Awk,记录的相反顺序

[英]Bash Awk, Reverse order of records

Hey everyone I am making an awk bash script that will take an input text file such as: 大家好,我正在制作awk bash脚本,它将使用输入文本文件,例如:

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(1)命令。

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). 如果需要第一列的非字母排序,则需要-n开关(以数字方式排序)。 The -r switch just reverses the output (ascending/descending). -r开关仅反转输出(升/降)。

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 如果您不必使用awk ,则可以轻松完成以下操作: tac file

Here is an awk variation: 这是awk变体:

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解决方案:

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

or sed sed

$ sed '1!G;h;$!d' file
4444 Rob Black
3333 Chris Williams
2222 Charlie Rogers
1111 Joe Brown

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM