Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Using sed to Print Specific Lines in a File

using-sed-to-print-specific-lines-in-a-file.jpg

This could be handy when a stack trace in a large file points to a specific line, now you can see those lines quickly.

Quick Jump:

Every once in a while I’m doing contract work where I end up having a massive 200,000+ line file, maybe it’s a SQL dump or something else but if a command that processes that file doesn’t work and a stack trace says there’s a problem on line 134,810 sometimes I don’t want to open the whole file in an editor. I might even be in a container where no editor is installed.

You can use sed -n 50p myfile to output just line 50 specifically, or if you want to see a range of lines you can do sed -n 50,100p myfile to see those lines. We use -n so sed doesn’t print the whole file and the p at the end tells sed to print matching lines.

The range is inclusive so 5,8 would include lines 5, 6, 7 and 8.

You can do more advanced ranges too, such as using regular expressions using sed -n '/PATTERN_1/,/PATTERN_2/p' myfile. You can also do something from let’s say line 10 to the end of the file with sed -n '10,$p' myfile where $ is the last line. Make note to use single quotes here otherwise your shell will try to interpret $p as a variable and it will be empty.

You can even print multiple sets of lines and ranges too using ; to split them up. For example sed -n '3,11p;35p' myfile would print lines 3-11 and also line 35.

Of course if you have a small file you can easily cat it or even use less for a decently small file but every once in a while using sed helps a lot! It’s a versatile tool.

# Demo Video

Timestamps

  • 0:17 – Real world use case
  • 0:38 – Getting 1 line or a range of lines
  • 1:07 – Regular expressions
  • 2:01 – Different groups of lines

When was the last time you used sed to preview lines in a file?

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments