Use head and tail to Get the Start or End of Text in Bash

Cameron Nokes
InstructorCameron Nokes
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

Head and tail are handy tools for getting just the beginning or end of a text stream. In this lesson, we’ll look at getting the first or last lines from the beginning or end of text.

Instructor: [00:00] We can use the head command to get the start of text. Let's get the first 10 lines of my package.json file here.

$ [00:07] head package.json. I've pulled the preact repository. By default, if I run head and pass it a file, it will get the first 10 lines of that file and then cut it off right there.

[00:19] To change how many lines you get, you can pass the -n flag, so if I want the first three lines, I can do that, and get three lines. I can even abbreviate that and do a dash and my number and pass the file here again. It does the same thing.

[00:39] Head has another handy flag, the -c flag, which stands for byte counts. I do byte count 10, and we see it gets the first 10 bytes and it cuts it off. This is occasionally useful if you know exactly how many bytes you need. You can get that from the very start of the file.

[00:58] Head can be especially useful if you pipe another command to it. For example, if I want to check the response of a curl and I know what I'm looking for is near the top of the long response, this is your curl --silent. I'll pipe it to hen and I get the first five lines so I got the beginning of the HTML document.

[01:17] The inverse of head is tail, so tail will get the end of the file or text stream. For example, I can use git tag --list to list all of the tags in a project. If I wanted to get the latest tag, I could do git tag sort = creatordate. If I wanted the last one there, I could pipe it to tail and then just say I just want one and that will be the last. This syntax works for tail as well.

egghead
egghead
~ 9 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today