guy mograbi
guy mograbi

Reputation: 28608

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

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

Upvotes: 7

Views: 8385

Answers (4)

tripleee
tripleee

Reputation: 189327

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

Upvotes: 1

gniourf_gniourf
gniourf_gniourf

Reputation: 46813

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}

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Another awk solution,

$ awk -v RS= '{gsub(/\n+/, "\\n")}1' file
-----BEGIN CERTIFICATE-----\nMIIDBjCCMIIDB\nMIIDBjCCMIIDB\n    .... \nMIIDBjCCMIIDB==\n-----END CERTIFICATE-----

Through sed,

$ sed ':a;N;$!ba;s/\n/\\n/g' file
-----BEGIN CERTIFICATE-----\nMIIDBjCCMIIDB\nMIIDBjCCMIIDB\n    .... \nMIIDBjCCMIIDB==\n-----END CERTIFICATE-----

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85775

One way using awk:

$ awk '$1=$1' ORS='\\n' file
-----BEGIN CERTIFICATE-----\nMIIDBjCCMIIDB\nMIIDBjCCMIIDB\n....\nMIIDBjCCMIIDB==\n-----END CERTIFICATE-----\n

Upvotes: 11

Related Questions