How to display a file with multiple lines as a single string with escape chars (\n)

拈花ヽ惹草 提交于 2019-12-25 04:15:54

问题


In bash, how I can display the content of a file with multiple lines as a single string where new lines appears as \n.

Example:

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

I need to get the content as this "line 1\nline2" with bash commands.

I tried using a combinations of cat/printf/echo with no success.


回答1:


You can use bash's printf to get something close:

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

and in bash 4.4 there is a new parameter expansion operator to produce the same:

$ foo=$(<file.txt)
$ echo "${foo@Q}"
$'line1\nline2'



回答2:


$ cat file.txt 
line 1
line 2
$ paste -s -d '~' file.txt | sed 's/~/\\n/g'
line 1\nline 2

You can use paste command to paste all the lines of the serially with delimiter say ~ and replace all ~ with \n with a sed command.




回答3:


you could try piping a string from stdin or file and trim the desired pattern...

try this:

cat file|tr '\n' ' '

where file is the file name with the \n. this will return a string with all the text in a single line.

if you want to write the result to a file just redirect the result of the command, like this.

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

here is another example: How to remove carriage return from a string in Bash




回答4:


Without '\n' after file 2, you need to use 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

With '\n' after line 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



回答5:


This tools may display character codes also:

$ 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


来源:https://stackoverflow.com/questions/40540478/how-to-display-a-file-with-multiple-lines-as-a-single-string-with-escape-chars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!