1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Use head and tail to get the start or end of text in bash

    Cameron NokesCameron Nokes

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    $ 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.

    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.

    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.

    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.

    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.