简体   繁体   English

使用awk打印选定的行

[英]use awk for printing selected rows

I have a text file and i want to print only selected rows of it. 我有一个文本文件,我只想打印它的选定行。 Below is the dummy format of the text file: 下面是文本文件的伪格式:

Name Sub Marks percentage
A     AB  50     50
Name Sub Marks percentage
b     AB  50     50
Name Sub Marks percentage
c     AB  50     50
Name Sub Marks percentage
d    AB  50     50

I need the output as:(Don't need heading before every record and need only 3 columns omitting "MARKS") 我需要的输出为:(不需要每条记录前的标题,只需要3列就省略了“ MARKS”)

Name Sub  percentage
A     AB     50
b     AB     50
c     AB     50
d     AB      50

Please Suggest me a form of awk command using which I can achieve this, and thanks for supporting. 请建议我使用awk命令的形式,我可以使用该形式来实现此目标,并感谢您的支持。

awk solution: awk解决方案:

awk 'NR==1 || !(NR%2){ print $1,$2,$4 }' OFS='\t' file
  • NR==1 || !(NR%2) NR==1 || !(NR%2) - considering only the 1st and each even line NR==1 || !(NR%2) -仅考虑第一行和每个偶数

  • OFS='\\t' - output field separator OFS='\\t'输出字段分隔符

The output: 输出:

Name    Sub percentage
A   AB  50
b   AB  50
c   AB  50
d   AB  50

You can use: 您可以使用:

awk '(NR == 1) || ((NR % 2) == 0) {print $1" "$2" "$4}' inputFile

This will print columns one, two and four but only if the record number is one or even. 这将打印第一,第二和第四列,但前提是记录号为一或偶数。 The results are: 结果是:

Name Sub percentage
A AB 50
b AB 50
c AB 50
d AB 50

If you want it nicely formatted, you can use printf instead: 如果您希望其格式正确,则可以改用printf

awk '(NR == 1) || ((NR % 2) == 0) {printf "%-10s %-10s %10s\n", $1, $2, $4}' inputFile

Name       Sub        percentage
A          AB                 50
b          AB                 50
c          AB                 50
d          AB                 50

In case that input file has a slight different format above solution will fail. 如果输入文件的格式略有不同,上述解决方案将失败。 For example: 例如:

Name Sub Marks percentage
A     AB  50     50
Name Sub Marks percentage
b     AB  50     50
c     AB  50     50
Name Sub Marks percentage
d    AB  50     50

In such a case, something like this will work in all cases: 在这种情况下,类似的方法在所有情况下都适用:

$ awk '$0!=h;NR==1{h=$0}' file1
Name Sub Marks percentage
A     AB  50     50
b     AB  50     50
c     AB  50     50
d    AB  50     50

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

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