Issue
I create a file using nano file.txt
. I typed in Hello
hit enter and then typed mate
so the input file looks like this:
Hello
mate
How do I replace the linefeed character in this file with \\n
so that I can substitute this value later when I build valid json data, i.e. the expected output would be:
{"output":"Hello\\nmate"}
Right now this is my bash script
#!/bin/bash
expected_output=$(<file.txt)
expected_output=${expected_output//\\/\\\\}
JSON_FMT='{"output":"%s"}'
printf "%s" "$expected_output" >> aaa.txt
the file aaa.txt
is being read by a different programming language where I decode the json.
Solution
If your input looks like this:
$ cat file
Hello
mate
and you want to replace all LineFeeds except the last one (assuming it's a valid POSIX text file) with \\n
then you could do the following using any awk:
$ awk '{rec=rec sep $0; sep="\\\\n"} END{printf "{\"output\":\"%s\"}\n", rec}' file
{"output":"Hello\\nmate"}
Original answer when the OP said their input looked like:
$ cat file
Hello\nmate
Using any sed:
$ sed 's/\\/\\\\/' file
Hello\\nmate
$ sed 's/\(.*\)\\\(.*\)/{"output":"\1\\\\\2"}/' file
{"output":"Hello\\nmate"}
Answered By - Ed Morton Answer Checked By - Mildred Charles (WPSolving Admin)