script to count lines
Hello!
I would like to ask your opinion: I made a script to count the lines of a file like that: #!/bin/bash NR_LINES=$(nl $FILE | tail -1) echo "The file $FILE has $NR_LINES lines" >no_lines.txt the problem is , when i execute ./count_lines.sh /home/.../file.txt it shows me the nr of lines without counting the empty lines ... What i can i add to the script to be fine? i tried all the solutions on google but no result Have a nice day,, |
By default nl numbers non empty lines only. To number empty lines you have to use the -ba option.
Code:
nl -ba $FILE |
Code:
NR_LINES=$(cat $FILE | wc -l) |
Quote:
Code:
wc -l < file |
Other methods, using awk and sed:
Code:
awk 'END{print NR}' file |
Ghostdog++ - no need for cat. Using awk or sed will also avoid the leading blank spaces that wc -l leaves you with.
Code:
#!/bin/bash Code:
Awk: There are 18 lines in array. |
Fine. I'll just do it in pure Bash :)
Code:
#!/usr/bin/env bash |
|
Hi!!!
Thanks for your answers...it went.. but,actually, i had to show the nr of lines for more files, and i wrote this: #!/bin/bash i=1 while test $i -le $#; do NR_LINES=$(cat $i | wc -l) echo "File $i has $NR_LINES lines" >>out.txt ((i++)) done When i write " ./count_lines.sh file1 file2 " it always says: cat: 1: No such file or directory cat: 2:... ... What is the problem? Thanks for your answers!!!!!! |
i forgot to mention that the path of the files are well-written (not this is the problem)
|
I would try something like this:
#!/bin/bash #i=1 #while test $i -le $#; do until [ -z "$1" ]; do NR_LINES=$(cat $1 | wc -l) echo "File $1 has $NR_LINES lines" shift #((i++)) 1. Ultimately you were getting the "cat: 1: No such file or directory" messages because you were trying to cat '$i', which was always going to 1, 2, 3...etc and not the actual file names passed in. So instead, we will always use $1 to refer to the current command line argument. At the end of the loop we use the shift command, which will move the next command line argument into $1. So something like this: 1st time through loop: $1 = file1 $2 = file2 $3 = file3 2nd time through loop: $1 = file2 $2 = file3 3rd time through loop: $1 = file3 2. Instead of this using the $i variable within a while statement, you can use the: until [ -z "$1" ]; do to loop through the arguments. That way you don't have to keep track of them through an extra variable. Information from note 2 taken from: http://tldp.org/LDP/abs/html/othertypesv.html --Shaun |
I still don't understand why you need wc. I would be willing to wager the following is faster. Not that it most likely matters:
Code:
#!/usr/bin/env bash |
Code:
cat files | grep -c '.*' ta0kira |
Quote:
Code:
grep -c ".*" files |
Quote:
ta0kira |
All times are GMT -5. The time now is 12:14 AM. |