我是awk命令的新手,还在尝试使用它,我正在尝试显示文件的多行内容,比如第3-5行,然后向后显示它。因此,对于给定的文件:
Hello World
How are you
I love computer science,
I am using awk,
And it is hard.
并且它应该输出:
science, computer love I
awk, using am I
hard. is it And
朝着正确方向迈出的任何一步都将是有益的!
发布于 2018-02-09 09:08:22
您可以使用以下awk
命令实现您的目标:
输入:
$ cat text
Hello World
How are you
I love computer science,
I am using awk,
And it is hard.
输出:
$ awk 'NR<3{print}NR>=3{for(i=0; i<NF; i++){printf "%s ",$(NF-i);} printf "\n";}' text
Hello World
How are you
science, computer love I
awk, using am I
hard. is it And
说明:
NR<3{print}
将从第三行开始在正确的orderNR>=3{for(i=0; i<NF; i++){printf $(NF-i)" ";} printf "\n";}'
中打印前2行,您对NF
标识的所有字段进行循环,然后从最后一个字段到第一个字段($NF
是最后一个字段,$1
是第一个字段)一个接一个地打印它们,然后用空格分隔每个字段。最后,但并非最不重要的,在循环之后,您将打印和EOL char。现在,如果您不需要打印前两行,请使用:
$ awk 'NR>=3{for(i=0; i<NF; i++){printf "%s ",$(NF-i);} printf "\n";}' text
science, computer love I
awk, using am I
hard. is it And
对于要仅打印范围(3-5)的更多行的文件,请使用:
$ awk 'NR>=3 && NR<=5{for(i=0; i<NF; i++){printf "%s ",$(NF-i);} printf "\n";}' text
发布于 2018-02-09 11:17:26
在同样的情况下,遵循awk
可能会对您有所帮助,在这里,我使用start
和end
变量来仅获取OP需要打印的那些行。
awk -v start=3 -v end=5 'FNR>=start && FNR<=end{for(;NF>0;NF--){printf("%s%s",$NF,NF==1?RS:FS)}}' Input_file
输出如下所示。
science, computer love I
awk, using am I
hard. is it And
解释:现在也为解决方案添加了解释。
awk -v start=3 -v end=5 ' ##Mentioning variables named start and end where start is denoting the starting line and end is denoting end line which we want to print.
FNR>=start && FNR<=end{ ##Checking condition here if variable FNR(awk out of the box variable) value is greater than or equal to variable start AND FNR value is less than or equal to end variable. If condition is TRUE then do following:
for(;NF>0;NF--){ ##Initiating a for loop which starts from value of NF(Number of fields, which is out of the box variable of awk) and it runs till NF is 0.
printf("%s%s",$NF,NF==1?RS:FS)} ##Printing value of NF(value of field) and other string will be either space of new line(by checking when field is first then print new line as print space).
}
' Input_file ##Mentioning Input_file name here.
发布于 2018-02-09 11:59:43
$ cat tst.awk
NR>2 && NR<6 {
for (i=NF; i>0; i--) {
printf "%s%s", $i, (i>1?OFS:ORS)
}
}
$ awk -f tst.awk file
science, computer love I
awk, using am I
hard. is it And
https://stackoverflow.com/questions/48696038
复制相似问题