简体   繁体   中英

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")

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 solution:

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

  • OFS='\\t' - output field separator

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:

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

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.

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