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.