Reputation: 548
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
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
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
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
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
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