How to remove the literal string "\n" (not newlines) from a variable in bash?
Asked Answered
C

3

6

I'm pulling some data from a database and one of the strings I'm getting back is in one line and contains multiple instances of the string \n. These are not newline characters; they are literally the string \n, i.e. backslash+en, or hex 5C 6E.

I've tried using sed and tr to remove them however they don't seem recognize the string and don't effect the variable at all. This has been a difficult problem to search for on google as all the results I get back are about how to remove newline characters from strings which is not what I need.

How can I remove these strings from my variable in bash?

Example data:

\n\nCreate a URL where the client can point their web browser to. This URL should test the following IP addresses and ports for connectivity.

Example failed command:

echo "$someString" | tr '\\n' ''

Operating system: Solaris 10

Possible Duplicate - Except this is in python

Conservancy answered 26/7, 2016 at 21:5 Comment(2)
Can you give us an example of the input data, and show us what you tried?Dying
echo "one\\ntwo" | perl -wpe 's/\\n//g'. (The \\n in input is to create such a string.)Perl
A
5

I suspect you just didn't escape the \ correctly in the replacement when using sed. Also note that tr is not well-suited for this task. Finally, if you want to replace \n in a variable, then Pattern substitution (a form of Parameter Expansion) is your best option.

To replace \n in a variable, you can use Bash pattern substitution:

$ text='hello\n\nthere\nagain'
$ echo ${text//\\n/}
hellothereagain

To replace \n in standard input, you can use sed:

$ echo 'hello\n\nthere\nagain' | sed -e 's/\\n//g'
hellothereagain

Notice the \ escaped in the pattern as \\ in both examples.

Artair answered 26/7, 2016 at 21:12 Comment(0)
S
3

The tr utility will only work with single characters, transliterating them from one set of characters to another. This is not the tool you want.

With sed:

newvar="$( sed 's/\\n//g' <<<"$var" )"

The only thing worth noting here is the escaping of the \ in \n. I'm using a here-string (<<<"...") to feed the value of the variable var into the standard input of sed.

Stet answered 26/7, 2016 at 21:9 Comment(0)
C
1

You don't need external tools for this, bash can do it trivially and efficiently on it's own:

$ someString='\n\nCreate a URL where the client can point their web browser to.  This URL should test the following IP addresses and ports for connectivity.'

$ echo "${someString//\\n/}"
Create a URL where the client can point their web browser to.  This URL should test the following IP addresses and ports for connectivity.
Cienfuegos answered 26/7, 2016 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.