Bash: How to Replace Newline with Comma (With Example)


You can use the following syntax to replace newlines with commas in Bash:

tr '\n' ',' < city_names.txt > new_names.txt

This particular example replaces all newlines with commas in the file named city_names.txt and outputs the results to a new file named new_names.txt.

Note that the tr operator is used to translate or substitute one pattern for another in Bash.

By using the tr operator, we specify that we want all newlines ( \n ) replaced with commas ( , ) instead.

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

Example: How to Replace Newlines with Commas in Bash

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

  • c:/users/bobbi/city_names.txt

The file contains the names of various U.S. cities:

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

We can use the following syntax to do so:

tr '\n' ',' < c:/users/bobbi/city_names.txt > c:/users/bobbi/new_names.txt

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

Bash replace newlines with commas

If we navigate to where the file is saved on our computer, we can view the contents of the file:

We can see that all of the newlines in the file have been replaced with commas instead.

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

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