Table of Contents
Using tr
Command
Use the tr
command to remove the new line from a string. The tr
command is used for character translation or deletion.
1 2 3 4 |
echo "Hello World" | tr -d '\n' |
1 2 3 |
HelloWorld |
In the above, we have a string that contains a newline character between Hello
and World
. The echo
command displays the string, including the newline character. The |
symbol is called a pipe and is used to pass the output of the echo
command as input to the tr
command.
In this case, we want to delete any occurrences of the specified character. The -d '\n'
option tells the tr
command to delete any occurrences of the specified character, which is the newline character \n
, resulting in a string with no newlines.
Using the sed
Command
Use the sed
command to remove the new line from a string.
1 2 3 4 |
echo "Hello World" | sed ':a;N;$!ba;s/\n//g' |
1 2 3 |
HelloWorld |
The sed
command is a powerful text editor that can be used to perform a wide variety of text manipulation tasks. For example, the previous section taught us about the echo
command and the |
symbol. The code in this section is similar to the code example in the previous section, but here we’re using the sed
command to remove newlines from a string.
The :a;N;$!ba;s/\n//g
command is the sed
command itself, and it has two parts: The first part, :a;N;$!ba;
is a loop that reads in the entire string, line by line, and stores it in a buffer. The second part, s/\n//g
, is the substitution command that replaces every occurrence of the newline character \n
with nothing //
, effectively removing it from the string.
Using the awk
Command
Use the awk
command to remove the new line from a string.
1 2 3 4 |
echo "Hello World" | awk '{ printf "%s", $0 }' |
1 2 3 |
HelloWorld |
The awk command is one of the powerful text processing tools that can perform complex data analysis tasks. In this method, we’re using awk
to remove new lines from the string. Again, we used the echo
command and the |
symbol. For example, in the '{ printf "%s", $0 }'
command, "%s"
is a formatting string used by the printf
function.
The %s
format specifier prints a string of characters, which is stored in the $0
variable. So when the printf
function is called with the %s
format specifier and the $0
variable as an argument, it will print the entire input line as a string without any trailing newline character.
Conclusion
So, removing newline characters from a string is a common task in Bash, and there are multiple ways to achieve this. We explored three popular methods for removing newlines from strings in Bash, including tr
, sed
, and awk
commands, and provided sample code to demonstrate how to use them.
The tr
, sed
, and awk
commands are powerful text manipulation tools that can process and transform data in various ways. By mastering these tools, you can gain greater control over the data you work with and automate many repetitive and time-consuming tasks.