Skip to content

Read First or Last N Lines from File

Read the first of the last lines from a file on Windows, Linux and macOS

Sometimes you might need to preview a specific number of lines from the beginning or the end of a file.

For example, you may want to preview the five initial lines of a log file or the last two lines of a CSV file.

Let’s see how to accomplish this on Windows, Linux, and macOS using command-line tools.

πŸŽ₯ Do you prefer a video instead? I’ve got you covered:

Windows

On Windows, you can use the following PowerShell command to read the first five lines:

Get-Content "example.txt" -Head 5

To read the last five lines, you can use the -Tail parameter:

Get-Content "example.txt" -Tail 5

Linux and macOS

To get the first five lines on Linux and macOS, you can use the head command:

head -n 5 "example.txt"

To read the last five lines, you can use the tail command:

tail -n 5 "example.txt"

Happy coding πŸ’œ


Let me know what you think about this article in the comments section below.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.   
  

Comments