snacks snacks - 4 months ago 7
Bash Question

Converting CSV to string in bash

I'm trying to convert a csv into a space-delimited string variable in bash and I'm having trouble figuring out how to get the info into a string.

How would I go about reading in and converting a csv that looks like this:

number1
number2
number3
etc


to a string
"number1 number2 number3 etc"
?

Thank you!

Answer

You can convert all newlines to spaces using tr:

tr '\n' ' ' <file.csv

If you want to reuse the output, save in a variable:

out=$(tr '\n' ' ' <file.csv)

Now you can get the output string by using "$out".