How to display a file with multiple lines as a single line with escape characters (\ n)

In bash, how can I display the contents of a file with multiple lines as a single line, where new lines are displayed as \n.

Example:

$ echo "line 1
line 2" >> file.txt

I need to get the contents as "line 1\nline2"using bash commands.

I tried to use combinations cat/printf/echowithout success.

0
source share
5 answers

You can use bash printfto get something close:

$ printf "%q" "$(< file.txt)"
$'line1\nline2'

and in bash4.4 there is a new parameter extension operator to get the same:

$ foo=$(<file.txt)
$ echo "${foo@Q}"
$'line1\nline2'
+4
source
$ cat file.txt 
line 1
line 2
$ paste -s -d '~' file.txt | sed 's/~/\\n/g'
line 1\nline 2

paste, say ~ ~ \n sed.

+1

stdin ...

:

cat file|tr '\n' ' '

file - \n. .

, , .

cat file|tr '\n' ' ' >> file2

: Bash

0

'\n' 2 echo -n

echo -n "line 1
line 2" > file.txt

od -cv file.txt
0000000   l   i   n   e       1  \n   l   i   n   e       2

sed -z 's/\n/\\n/g' file.txt
line 1\nline 2

'\n' 2

echo "line 1
line 2" > file.txt

od -cv file.txt
0000000   l   i   n   e       1  \n   l   i   n   e       2  \n

sed -z 's/\n/\\n/g' file.txt
line 1\nline 2\n
0

:

$ hexdump -v -e '/1 "%_c"' file.txt ; echo
line 1\nline 2\n

$ od -vAn -tc file.txt 
   l   i   n   e       1  \n   l   i   n   e       2  \n
0

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


All Articles