sed, how can I replace all newline characters in a given string or file with spaces?
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
N: appends the next line of input to the pattern space.
$!ba: if this is not the last line (
$!), return to (
b) the label
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:
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 '\n' ' ' < filename
To learn more about
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.
Here’s a quick look at how Sentry handles your personal information (PII).×
We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.Am I included?
We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII: