简体   繁体   中英

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

One way using awk :

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

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}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM