Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only the first 10 rows in my AWK script

Tags:

bash

csv

awk

I have a large CSV file. Basically what I want to do is display only the first 5 columns (which I can) but I also only want to display the first 10 rows, which is what I can't figure out. Right now this is the .awk file script I have:

"BEGIN {FS = ","}
{print $1", " $2", " $3", " $4", " $5}"

In Tera Term this is the command I use, which results in the first 5 columns of every row to be displayed: $awk -f example.awk example.csv

I have tried a couple of ways of using NR<=11 but that keeps coming up with error messages when trying to run on Tera Term.

Please help!

like image 462
lonewolf2288 Avatar asked May 08 '16 07:05

lonewolf2288


1 Answers

Try:

awk -F, '{print $1,$2,$3,$4,$5} NR==10{exit}' OFS=', ' file.csv

[Note that the awk code is in single-quotes, not double-quotes. That is necessary to prevent the shell from misinterpreting $1, etc., as shell variables and expanding them.]

How it works

  • -F, tells awk to use , as the field separator on input. This is equivalent to but much briefer than BEGIN {FS = ","}.

  • print $1,$2,$3,$4,$5 tells awk to print the first five columns. (See below for why the ", " strings aren't needed in this version.)

  • NR==10{exit} tells awk to exit on the tenth line.

  • OFS=', ' tells awk to use comma-space as the field separator on output. This setting makes much of the quoting in the original code unnecessary.

like image 79
John1024 Avatar answered Nov 15 '22 06:11

John1024