Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable for number of lines in a file

Tags:

bash

unix

I'm trying to put the number of lines in a file into an integer variable.

This is how i'm doing it

typeset -i x
x=`wc -l $1`

where $1 is the command line arg

The problem is that wc -l gives a number and the filename like: 5 blah

Is there a way to only put the number into x?

like image 394
JA3N Avatar asked Feb 27 '12 00:02

JA3N


People also ask

How do I count the number of lines in a file?

The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.


3 Answers

x=$(wc -l < "$1")

This avoids a useless use of cat and any forks, and would work on a path containing spaces and even newlines.

like image 163
l0b0 Avatar answered Oct 10 '22 04:10

l0b0


You could do cat $1 | wc -l instead.

Or wc -l $1 | cut -d " " -f 1.

like image 33
Oliver Charlesworth Avatar answered Oct 10 '22 04:10

Oliver Charlesworth


wc -l $1 | awk '{print $1}'

with awk

like image 30
Selman Ulug Avatar answered Oct 10 '22 05:10

Selman Ulug