How to Use sed to Replace newline with space


Often you may want to use sed to replace all newlines with spaces in a given file.

You can use the following basic syntax to do so:

sed -z 's/\n/ /g' city_names.txt

This particular example replaces all newlines with spaces in the file named city_names.txt.

Here is what the various sed commands do:

  • -z: Specifies that the input should be treated as a set of lines, each terminated by a zero byte
  • s: Specifies the pattern to “substitute”
  • g: Specifies that the pattern should be replaced “globally”, i.e. all occurrences should be replaced

By using the s operator, we specify that we want all newlines ( \n ) in the file to be replaced with spaces instead.

The following example shows how to use this syntax in practice.

Example: How to Use sed to Replace Newlines with Spaces

Suppose that we have a file saved in the following location on our computer:

  • c:/users/bobbi/city_names.txt

We can use the cat command to view the contents of this file:

We can see that the file contains the names of various U.S. cities with each city on its own line.

Suppose that we would like to replace each of the newlines in the file with spaces instead.

We can use the following syntax to do so:

sed -z 's/\n/ /g' city_names.txt

The following screenshot shows how to use this syntax in practice:

sed replace newlines with commas in file

In the output we can see that all of the newlines in the file have been replaced with spaces instead.

Each city name is now separated by a space instead of a newline.

We can also use the following syntax to save these results to a new file named new_city_names.txt:

sed -z 's/\n/ /g' city_names.txt > new_city_names.txt

The following screenshot shows how to use this syntax in practice:

sed replace newline with space and save to new file

Notice that when we use the cat command again to view the new file named new_city_names.txt, we can see that it contains the city names separated by spaces.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Replace Text in String
Bash: How to Replace Specific Line in File
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply