Printing and deleting the first line of a file using `sed`

You can use the command w to write some lines to a different output file. On Linux and many other unix variants, /dev/stdout is the program's standard output, which isn't where sed writes with the -i option. If your system doesn't have /dev/stdout or a variant such as /dev/fd/1, you can write to a named pipe.

sed -i -e '1 w /dev/stdout' -e '1d' file.txt

This answer is an extension of Gilles' answer.

Needing to write the address twice is not very DRY, and while it works fine for this example of just deleting the first line, that method becomes more problematic if you have a more complicated search pattern for lines you want to "extract" from a file. Instead of writing the address twice, you can use curly braces to do both the w and d commands on the same address. Using the original example, that would look like this:

sed -i -e '1{w /dev/stdout' -e 'd}' file.txt

or more generally:

sed -i -e '/some long regex/{w /dev/stdout' -e 'd}' file.txt

Tags:

Sed

Files