Getting and removing the first line and the last line in unix command.

Tomoharu Tsutsumi
1 min readJun 15, 2024

Sometimes forget them, so taking a note.

Getting the first line of a file

head -n 1 file.txt

For example, let’s see we have a file like below.

Flint is used for starting fires.
Some minerals like Flint are hard.
Another line without the keyword.

We can get

Flint is used for starting fires.

Getting the last line of a file

tail -n 1 file.txt

We can get

Another line without the keyword.

Removing the first line from a file

tail -n +2 file.txt

We can get

Some minerals like Flint are hard.
Another line without the keyword.

Removing the last line from a file

head -n -1 file.txt

We can get

Flint is used for starting fires.
Some minerals like Flint are hard.

Bonus

grep for each argument

echo "$pat" | xargs -I [] -n1 grep [] fruits.txt # $pat is apple cherry

Feel free to reach out to me on LinkedIn, which you can find below. Looking forward to connecting!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

Senior Software Engineer at two industry-leading startups ( Go | Ruby | TypeScript | JavaScript | Gin | Echo | Rails | React | Redux | Next)