Niranjan Kumar
Niranjan Kumar

Reputation: 15

how can we use sed command to write \n in a file?

When replacing string in file with other string having \n then when it replace it enters a line rather then writing \n in shell.

program-

string="status=\"translated\">NIRANJAN\\nKUMAR"
sed -i 's/status="translated">/'"$string"'   /g' text.txt

text files contains- status="translated">Fixes

output is:

status="translated">NIRANJAN
KUMAR

but i want status="translated">NIRANJAN\nKUMAR

please suggest me the steps. Thanks :)

Upvotes: 2

Views: 289

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74596

You already lost some backslashes during this assignment:

string="status=\"translated\">NIRANJAN\\nKUMAR"

The \\ will be reduced to a single \, so you end up with \n in your sed command, resulting in a newline (on some versions of sed, at least).

To preserve them, use single quotes around the string literal:

string='status="translated">NIRANJAN\\nKUMAR'

Now your sed command should behave as you expect.

Upvotes: 4

Related Questions