Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

How to count the lines of a file?

+3
−0

How to get the number of lines in a file?

I.e. for a file like this:

Line one
Line 2
Final line

I would like to do something like this:

$ count-lines /path/to/the/file/above
3
History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

2 answers

+6
−0

I think the typical way to do this uses wc ("word count") with the -l ("lines") option.

$ wc -l /path/to/file
    47 /path/to/file

$ wc -l </path/to/file
47

$ cat /path/to/file | wc -l
47

wc with no options prints the number of lines, words, and bytes, but -l can limit it to just lines. As a comment notes: "lines" is the number of newline characters, so you may be off-by-one if you don't have a trailing newline.

History
Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment thread

Newline characters (2 comments)
+1
−0

One way is to use grep:

$ grep --count ^ /path/to/the/file

The ^ character matches a start of a new line, so it basically counts the number of starting lines.

History
Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »