Counting Number of Lines in a File Using Grep and Wc

Count lines with integers in them using bash and wc -l

You can use grep after specifying a regular expression to identify integers.

For this particular case,
grep -E "^[0-9]+" | wc -l
should work.

Here,

^ means the start of the line

[0-9] means any number from 0 to 9

+ means one or more such digits

How to count lines in a document?

Use wc:

wc -l <filename>

This will output the number of lines in <filename>:

$ wc -l /dir/file.txt
3272485 /dir/file.txt

Or, to omit the <filename> from the result use wc -l < <filename>:

$ wc -l < /dir/file.txt
3272485

You can also pipe data to wc as well:

$ cat /dir/file.txt | wc -l
3272485
$ curl yahoo.com --silent | wc -l
63

Output and count total number of occurrences using grep in linux/nix

Use the uniq command to count the repetitions of a line. It requires the input to be sorted, so use sort first.

sort users.dat | uniq -c > user_total.dat

Filter and count the results at the same time with grep and wc

grep -E '^[ ]{0,9}\([0-9]{3}\) [0-9]{3}-[0-9]{4}[ ]{0,9}$' data.txt | sed 's/^[ \t]*//' > result-phonenumber-filter.txt
count=$(wc -l result-phonenumber-filter.txt)
echo "The number of line is :$count" >> result-phonenumber-filter.txt
$ cat result-phonenumber-filter.txt
(512) 258-6589
(205) 251-6584
(480) 589-9856
(303) 548-9874
(808) 547-3215
(270) 987-6547
(225) 258-9887
(314) 225-2543
(979) 547-6854
(276) 225-6985
The number of line is :10

How can I count all the lines of code in a directory recursively?

Try:

find . -name '*.php' | xargs wc -l

or (when file names include special characters such as spaces)

find . -name '*.php' | sed 's/.*/"&"/' | xargs  wc -l

The SLOCCount tool may help as well.

It will give an accurate source lines of code count for whatever
hierarchy you point it at, as well as some additional stats.

Sorted output:

find . -name '*.php' | xargs wc -l | sort -nr



Related Topics



Leave a reply



Submit