pablomolnar
pablomolnar

Reputation: 548

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

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.

Upvotes: 1

Views: 1266

Answers (5)

user8017719
user8017719

Reputation:

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

Upvotes: 0

chepner
chepner

Reputation: 531758

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'

Upvotes: 5

V. Michel
V. Michel

Reputation: 1619

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

Upvotes: 0

riteshtch
riteshtch

Reputation: 8769

$ 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.

Upvotes: 1

maco1717
maco1717

Reputation: 843

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

Upvotes: -1

Related Questions