Home » Infrastructure » Unix » How to get number of lines from a file into a shell variable
How to get number of lines from a file into a shell variable [message #98128] Fri, 19 March 2004 11:16 Go to next message
Swamy
Messages: 78
Registered: June 2002
Member
To get number of lines from a data file into a shell variable, I wrote as below in my shell script.

$countlines=`wc -l datafile.dat`

$echo countlines=$countlines

The result I am getting is:

$countlines=   4567 datafile.dat

     I need only the number 4567 as output, but not with the string datafile.dat. How can I achieve? I appreciate in advance for your help.

Thanks

Raj
Re: How to get number of lines from a file into a shell variable [message #98129 is a reply to message #98128] Sat, 20 March 2004 14:10 Go to previous messageGo to next message
William Robertson
Messages: 1643
Registered: August 2003
Location: London, UK
Senior Member
Two suggestions (both ksh):
/Users/williamr: set -A l $(wc -l zz)
/Users/williamr: print ${l[0]}
12
/Users/williamr: print ${l[1]}
zz

/Users/williamr: l=$(wc -l zz)       
/Users/williamr: print $l            
12 zz
/Users/williamr: l=${l% *}
/Users/williamr: print $l 
12
Re: How to get number of lines from a file into a shell variable [message #98130 is a reply to message #98129] Sat, 20 March 2004 14:24 Go to previous messageGo to next message
Swamy
Messages: 78
Registered: June 2002
Member
I got it and thank you so much for the help.
Re: How to get number of lines from a file into a shell variable [message #98615 is a reply to message #98129] Tue, 01 February 2005 21:09 Go to previous messageGo to next message
zen
Messages: 3
Registered: June 2004
Junior Member
Another method,

typeset -i a=1
while read line
do
a=$a+1
done
Re: How to get number of lines from a file into a shell variable [message #98616 is a reply to message #98615] Tue, 01 February 2005 21:24 Go to previous messageGo to next message
Jai Vrat Singh
Messages: 205
Registered: September 2002
Location: Singapore
Senior Member
lines=`wc -l filename | sed -e 's/[[ t]][[ t]]*/~/g'|cut -d'~' -f2`
Re: How to get number of lines from a file into a shell variable - me again [message #98617 is a reply to message #98616] Tue, 01 February 2005 22:29 Go to previous message
Jai Vrat Singh
Messages: 205
Registered: September 2002
Location: Singapore
Senior Member
line=`awk ' END { print NR } ' filename`
echo lines are $line
Previous Topic: get DB version
Next Topic: Query
Goto Forum:
  


Current Time: Fri Apr 19 16:31:59 CDT 2024