The Computer Oracle

How do I convert a bash array variable to a string delimited with newlines?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping

--

Chapters
00:00 How Do I Convert A Bash Array Variable To A String Delimited With Newlines?
00:19 Answer 1 Score 36
00:31 Accepted Answer Score 103
01:23 Answer 3 Score 11
01:59 Answer 4 Score 2
02:21 Thank you

--

Full question
https://superuser.com/questions/461981/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#bash #newlines

#avk47



ACCEPTED ANSWER

Score 103


Here's a way that utilizes bash parameter expansion and its IFS special variable.

$ System=('s1' 's2' 's3' 's4 4 4')
$ ( IFS=$'\n'; echo "${System[*]}" )

We use a subshell to avoid overwriting the value of IFS in the current environment. In that subshell, we then modify the value of IFS so that the first character is a newline (using $'...' quoting). Finally, we use parameter expansion to print the contents of the array as a single word; each element is separated by the first charater of IFS.

To capture to a variable:

$ var=$( IFS=$'\n'; echo "${System[*]}" )

If your bash is new enough (4.2 or later), you can (and should) still use printf with the -v option:

$ printf -v var "%s\n" "${System[@]}"

In either case, you may not want the final newline in var. To remove it:

$ var=${var%?}    # Remove the final character of var



ANSWER 2

Score 36


You can use printf to print each array item on its own line:

 $ System=('s1' 's2' 's3' 's4 4 4')
 $ printf "%s\n"  "${System[@]}"
s1
s2
s3
s4 4 4



ANSWER 3

Score 11


awk -v sep='\n' 'BEGIN{ORS=OFS="";for(i=1;i<ARGC;i++){print ARGV[i],ARGC-i-1?sep:""}}' "${arr[@]}"

or

perl -le 'print join "\n",@ARGV' "${arr[@]}"

or

python -c 'import sys;print "\n".join(sys.argv[1:])' "${arr[@]}"

or

sh -c 'IFS=$'\''\n'\'';echo "$*"' '' "${arr[@]}"

or

lua <(echo 'print(table.concat(arg,"\n"))') "${arr[@]}"

or

tclsh <(echo 'puts [join $argv "\n"]') "${arr[@]}"

or

php -r 'echo implode("\n",array_slice($argv,1));' -- "${arr[@]}"

or

ruby -e 'puts ARGV.join("\n")' "${arr[@]}"

that's all I can remind so far.




ANSWER 4

Score 2


Above solutions are pretty much it, but the original question asks for output to file:

$ a=(a b c d e)
$ ( IFS=$'\n'; echo "${a[*]}" ) > /tmp/file
$ cat /tmp/file
a
b
c
d
e
$

Notes: 1) 'echo' provides the final newline 2) If this file will just be read in by bash again, then declare -p may be the serialization wanted.