In this example
- Multiline input can be caputured by spreading openening and closing quote accross lines
- Newlines can be replaced using built-in bash text substitution
- The main trick is knowing that
$'\n'
is the way to specify the newling within the subsitution - Note, echo output of a var without quotation replaces newlines with spaces
$ t='1
> 2
> 3'
$ echo $t
1 2 3
$ $ echo "$t"
1
2
3
$ echo "${t//$'\n'/','}"
1,2,3
This could be leveraged futher with cat
and files
$ for i in {1..3}; do echo $i >> file.txt; done
$ f=$(cat file.txt)
$ echo "$f"
1
2
3
$ echo "${f//$'\n'/','}"
1,2,3
Take note of ${f//
instead of just ${f/
, becuase you want to subsitute all newlines, not just the first instance of a newline.
Lastly, beware that the above method loads file content into a bash variable (fine for small content). To handle subsitution in very large files, using cat into a var is a bad idea.
Reference (related)
Thanks @housni, indeed, need to substitute all, not just the first instance. Corrected the example and expanded it to 3 elements / 2 newlines, so the all vs first mistake is more obvious.