user15197125
user15197125

Reputation: 1

Storing \n as text not a newline in a linux file?

I want to store \n as text in a Linux file so that when I retrieve the file I get the following:

Hello\nWorld

instead of

Hello
World

I want to store \n as text and so that it does not represent a new line character. So I need to write the file so it interprets \n as text and not a newline.

I have tried \n but this still resulted in a new line.

I am writing the file using the printf linux command. It appends text to a Linux file.

Example: I currently do not have a file called file.txt

printf "text goes here" >> file.txt
printf " more text now" >> file.txt

Now I will have a file called file.txt with the text text goes here more text now

I have included the ascii tag but feel free to remove that tag if you do not think it is applicable because I was not sure..

Upvotes: 0

Views: 695

Answers (3)

Eduardo Bissi
Eduardo Bissi

Reputation: 184

The backslash \ is an escape character and will be interpreted together with the following character. The text \n is interpreted and replaced by a single character (Line Feed - LF).

To achieve what you want, escape the backslash with another one. So \\ is interpreted and replaced by a single \ and the following n character is not touched.

Upvotes: 0

choroba
choroba

Reputation: 241898

Backslash the backslash in printf

printf 'Hello\\nWorld' > file.txt

Or use '\n' as a second parameter that fills a template:

printf 'Hello%sWorld' '\n'

Upvotes: 0

Gal Gur-Arie
Gal Gur-Arie

Reputation: 394

echo 'hello\\nworld' > /tmp/1.txt

Upvotes: 1

Related Questions