How to Remove newline from String in Bash


You can use the following syntax to remove a newline from a string in Bash:

my_variable=$(echo $my_variable | tr -d '\n')

This particular example removes all newlines from the string stored in the variable named $my_variable.

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

By using the tr operator with -d we specify that we want all newlines ( \n ) in the string to be deleted.

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

Example: How to Remove Newline from String in Bash

Suppose that we create a variable named $my_variable that contains two newlines:

my_variable=$'hey \nthere \neveryone'
echo "$my_variable"

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

Suppose that we would like to remove each newline from the string.

We can use the following syntax to do so:

my_variable=$(echo $my_variable | tr -d '\n')
echo "$my_variable"

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

Bash remove newline from string

When we use the echo command to display $my_variable we can see that all of the newlines have been removed from the string.

By using the command tr -d ‘\n’ we are able to delete all newlines from the original string.

Related Tutorials

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

Bash: How to Replace Newline with Comma
Bash: How to Replace Text in String
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply