If you find yourself constantly having to remove lines from the middle of a file in Linux, there are a few simple steps you can take to make your life easier. ..


When you manage your own servers, one of the things you end up needing to do on a semi-regular basis is extract stuff from the middle of a file. Maybe it’s a log file, or you need to extra a single table from the middle of your MySQL backup file, like I did.

To figure out the line numbers, a simple grep -n command did the job (the -n argument outputs the line numbers). This made it easy to figure out what I needed to extract.

Results in something like this, which shows the line numbers over on the left side of the output. Piping everything into “more” makes sure that you can see the first line without it scrolling by. Now you’ve got the line number to start with, and probably the one to end with.

You could, of course, just pipe the output from grep into another file, like this:

In my case, that didn’t want to work, because I couldn’t import the resulting backup for some reason. So, I found a different way to extract the lines using sed, and this method did work.

Basically the syntax is like this, making sure to use the -n argument, and include the “p” after the second line number.

Some other ways you can pull out specific lines in the middle of a file? You could use the “head” command with the +number argument to just read through the first x lines of a file, and then use tail to extract those lines. Not the best option, lots of overhead. Simpler option? You can use the split command to turn the file into multiple files right at the line number you want, and then extract the lines using head or tail.

Or you can just use sed.