Replace newlines with spaces using `sed`

David Y.

The Problem

Using sed, how can I replace all newline characters in a given string or file with spaces?

The Solution

While sed is designed for use on single lines of text, it is possible to replace newline characters with spaces through the following method:

sed ':a;N;$!ba;s/\n/ /g' filename

The first part of this command (:a;N;$!ba;) gathers all of the file’s contents into sed’s pattern space:

  • :a: creates a label named a.
  • N: appends the next line of input to the pattern space.
  • $!ba: if this is not the last line ($!), return to (b) the label a (a).

This recursively loads the entire input into the pattern space. Once it’s loaded, we use a substitution to replace all newline characters with spaces:

`s/\n/ /g`

As can be seen from the complexity required to complete a relatively simple task, sed may not be the best tool to rely on when parsing and manipulating multi-line input. For this particular problem, we could achieve the same results with a far shorter tr command:

tr '\n' ' ' < filename

To learn more about sed and tr, view their respective manual pages by typing man sed or man tr into the terminal.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.