Artificial intelligent assistant

Replace in shell \n by \\n I'm looking how can I convert a string like that : foo\nbar into : foo\\nbar What I have seen so far is that `tr` can't do that because it's working only on chars, and I couldn't find any other solution working... Exemple : redgl0w@anarchy ~> cat test foo bar And I'm looking to get : redgl0w@anarchy ~> echo test foo\nbar

You can easily do this in perl:


perl -pe 's/\
/\\
/' file


If your string is in a variable, use:


perl -pe 's/\
/\\
/' <<<"$variable"


Or


printf '%s' "$variable" | perl -pe 's/\
/\\
/'


If you want, you can save it as a variable:


$ cat test
foo
bar
$ test=$(perl -pe 's/\
/\\
/g' test)
$ echo "$test"
foo\
bar\



Or, if you don't want to convert the final, trailing newline, and assuming your file is small enough to fit in RAM, you can do:


$ test=$(perl -0777 -pe 's/\
/\\
/g; s/\\
$/\
/' test);
$ echo "$test"
foo\
bar


Or, a better way suggested by Rakesh Sharma in the comments which doesn't require holding the file in memory:


$ perl -lpe '$\ = eof ? qq(\
) : q(\
);s/\
/\\
/;' test
foo\
bar

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy 5a67fe6a01598a6be8da0894d6a2bd7d