3

I want to know how to get the number of rows in a text file using Linux. I have tried "wc " and "wc -l ", but both display only the number of lines (columns) not the rows. Any idea?

Adam Majdi
  • 107
  • 1
  • 1
  • 11
  • What do you mean by rows and columns in a text file? Are you talking about a delimited file? – codeforester Feb 02 '17 at 02:42
  • Thanks! No, I mean how I can know the dimension of a text file. The file has numbers with one space between them: Example: 1 5 2 9 3 2 8 9 6 3 4 8 5 8 3 So, I want to know the number of rows of that file (in this example is 3) – Adam Majdi Feb 02 '17 at 04:15
  • I think you are confusing lines, columns and rows. Lines and rows are the same, that is horizontal lines. Columns are the vertical ones. What do you want exactly? Provide an example with multiple lines and columns and what is your desired output. – Zumo de Vidrio Feb 02 '17 at 07:59
  • Thanks! Just to make it simple: I want to know the dimensions of a text file using Linux. i.e. number of rows and number of columns. – Adam Majdi Feb 02 '17 at 16:09
  • 2
    Does this answer your question? [How do I count the number of rows and columns in a file using bash?](https://stackoverflow.com/questions/5761212/how-do-i-count-the-number-of-rows-and-columns-in-a-file-using-bash) – Josh Correia Oct 15 '20 at 23:00

2 Answers2

11

wc -l < <filename> displays lines for me

example file with numbers 1 - 7

outputs:

scottsmudger@ns207588:~ $wc -l < test
7

From the man page:

-l, --lines
    print the newline counts
ScottSmudger
  • 351
  • 2
  • 8
0

if you want to get the number of fields in each line you can use awk :

  • awk reads a line from the file and puts it into an internal variable called $0 . Each line is called record. By default, every line is terminated by a newline.
  • Then, every record or line is divided into separate words or fields. Every word is stored in numbered variables $1 , $2 , and so on. There can be as many as 100 fields per record.
  • awk has an internal variable called IFS (Internal Field Separator). IFS is normally whitespace.

In this case we can use an internal built-in variable called NF, which will keep track of field numbers. Typically, the maximum field number will be 100.

awk '{  print NF }' file_name

this command will print the number of columns in each line