Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert multiline file into a string in bash with newline character?

Tags:

linux

bash

How can I convert a file with multiple lines to a string with \n characters in bash?

For example - I have a certificate that I need to configure in my configuration JSON file so instead of having

-----BEGIN CERTIFICATE-----
MIIDBjCCMIIDB
MIIDBjCCMIIDB
    .... 
MIIDBjCCMIIDB==
-----END CERTIFICATE-----

I will have

-----BEGIN CERTIFICATE-----\nMIIDBjCCMIIDB\nMIIDBjCCMIIDB\n....\nMIIDBjCCMIIDB==\n-----END CERTIFICATE-----
like image 402
guy mograbi Avatar asked Oct 19 '14 14:10

guy mograbi


People also ask

How do I create a multiline string in bash?

Bash Escape Characters For example, if we have a multiline string in a script, we can use the \n character to create a new line where necessary. Executing the above script prints the strings in a new line where the \n character exists.

How do I convert multiple lines to one line in Linux?

In the two commands above, we passed two options to the paste command: -s and -d. The paste command can merge lines from multiple input files. By default, it merges lines in a way that entries in the first column belong to the first file, those in the second column are for the second file, and so on.

How do I echo multiple lines in bash?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.


3 Answers

One way using awk:

$ awk '$1=$1' ORS='\\n' file
-----BEGIN CERTIFICATE-----\nMIIDBjCCMIIDB\nMIIDBjCCMIIDB\n....\nMIIDBjCCMIIDB==\n-----END CERTIFICATE-----\n
like image 115
Chris Seymour Avatar answered Nov 15 '22 07:11

Chris Seymour


Bash has simple string substitution.

cert=$(cat file)
echo "${cert//$'\n'/\\n}"

I originally had '\n' in single quotes in the substitution part, but I took them out based on testing on Bash 3.2.39(1) (yeah, that's kinda old).

like image 34
tripleee Avatar answered Nov 15 '22 06:11

tripleee


A pure bash (with Bash≥4) possibility that should be rather efficient:

mapfile -t lines_ary < file
printf -v cert '%s\\n' "${lines_ary[@]}"

Check that it works:

echo "$cert"

One thing to note is that you will have a trailing \n. If that's not a concern, you're good with this method. Otherwise, you may get rid of it by adding the following line just after the printf -v statement:

cert=${cert%\\n}
like image 44
gniourf_gniourf Avatar answered Nov 15 '22 05:11

gniourf_gniourf