bash/sh: sed and the Newline Character \n

Practice



The problem: we need to use sed to replace newline characters with some other characters (for example, spaces). But what can you do - sed doesn't understand the \n escape sequence and doesn't want to cooperate with us.

Yes, the sed manual says exactly that - it won't work with \n in its expressions. But there's a workaround - use the tr construct:

echo -en "This\nis\nmultiline\nstring" | tr '\n' '_'
This_is_multiline_string

As we can see, tr successfully replaced the \n newline character with underscores, which sed will now be able to handle.


The opposite situation is also possible - when you need to replace certain characters with a newline. Here's an example:

echo "filename1 filename2 filename3" | tr ' ' '\n'
filename1
filename2
filename3

In this example, tr will replace all spaces with newlines.

Comments

Админ 09-06-2020
Пожалуйста)
Toronto 08-06-2020
Класс, спасибо.

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "LINUX operating system"

Terms: LINUX operating system