Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

sed

awk

perl

tr

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

like image 345
Void Avatar asked Jul 26 '16 21:07

Void


People also ask

How do I remove a new line character from a variable in UNIX?

dt=${dt%$'\n'} # Remove a trailing newline. dt="${dt% }" # Remove a trailing newline. Save this answer.

How do I remove something from a string in Bash?

The tr command (short for translate) is used to translate, squeeze, and delete characters from a string. You can also use tr to remove characters from a string. For demonstration purposes, we will use a sample string and then pipe it to the tr command.

Which command prevents new line in Bash?

Solution. Using printf it's easy—just leave off the ending \n in your format string. With echo, use the -n option.

How do I echo a newline in Bash?

The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.


1 Answers

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.

like image 118
janos Avatar answered Oct 02 '22 08:10

janos