How to remove literal string "\ n" (and not newline characters) from a variable in bash?

I pull some data from the database, and one of the rows that I return is on the same row and contains multiple instances of the row \n. These are not newlines; they literally represent a string \n, that is, a backslash + en or hex 5C 6E.

I tried using sed and tr to remove them, but they do not seem to recognize the string and do not affect this variable at all. This was a difficult problem to search on google, since all the results that I am returning about relate to how to remove newline characters from strings that I don't need.

How to remove these lines from my variable in bash?

Sample 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.

An example of a failed command:

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

: Solaris 10

- python

+4
3

, \ sed. , tr . , \n , ( ).

\n , Bash:

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

\n , sed:

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

\ \\ .

+4

tr , . , .

sed:

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

, , - \ \n. - (<<<"...") var sed.

+3

You do not need external tools for this, bash can do this trivially and efficiently:

$ 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.
+1
source

Source: https://habr.com/ru/post/1649216/


All Articles