Sentry Answers>Linux>

Replace newlines with spaces using `sed`

Replace newlines with spaces using `sed`

David Y.

The ProblemJump To Solution

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:

Click to Copy
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:

Click to Copy
`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:

Click to Copy
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.

  • ResourcesWhat is Distributed Tracing
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

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.

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