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-----
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.
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.
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.
One way using awk
:
$ awk '$1=$1' ORS='\\n' file
-----BEGIN CERTIFICATE-----\nMIIDBjCCMIIDB\nMIIDBjCCMIIDB\n....\nMIIDBjCCMIIDB==\n-----END CERTIFICATE-----\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).
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With