1

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.

pablomolnar
  • 528
  • 6
  • 14

5 Answers5

4

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'
chepner
  • 497,756
  • 71
  • 530
  • 681
1
$ 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.

riteshtch
  • 8,629
  • 4
  • 25
  • 38
0

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
V. Michel
  • 1,599
  • 12
  • 14
0

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
-1

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

Community
  • 1
  • 1
maco1717
  • 823
  • 10
  • 26