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
  • 509
  • 5
  • 14

5 Answers5

5

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'
done
  • 6,370
  • 27
  • 49
chepner
  • 446,329
  • 63
  • 468
  • 610
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,439
  • 4
  • 21
  • 36
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,579
  • 11
  • 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
done
  • 6,370
  • 27
  • 49
-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
  • 793
  • 8
  • 25