How to Use awk to Replace newline with Space


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

You can use the following basic syntax to do so:

awk -v RS= '{$1=$1}1' city_names.txt

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

This syntax works by using the RS command to set the record separator to paragraph mode, which automatically replaces any newlines with spaces.

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 named city_names.txt that contains the name of one U.S. city on each line of the file.

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

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:

awk -v RS= '{$1=$1}1' city_names.txt

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

awk replace newlines with spaces

We can see that each newline has been replaced with a space instead.

Note that if you’d like to save the changes to the file in-place then you use the following syntax:

awk -i inplace -v RS= '{$1=$1}1' city_names.txt

This will replace all newlines with spaces in the city_names.txt file in-place.

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