read line from file and save them in a comma separated string to a variable
bash, cat, variables
Solution
name_list=""
for name in `cat file.txt`
do VAR="$name_list,$i"
done
EDIT: this script leaves a "," at the beginning of name_list. There are a number of ways to fix this. For example, in bash this should work:
name_list=""
for name in `cat file.txt`; do
if [[ -z $name_list ]]; then
name_list="$i"
else
name_list="$name_list,$i"
fi
done
RE-EDIT: so, thanks to the legitimate complaints of Fredrik:
name_list=""
while read name
do
if [[ -z $name_list ]]; then
name_list="$name"
else
name_list="$name_list,$name"
fi
done < file.txt
Problem
I want to read lines from a text file and save them in a variable. ``` cat ${1} | while read name; do namelist=${name_list},${name} done ``` the file looks like this: ``` David Kevin Steve etc. ``` and i want to get this output instead David, Kevin, Steve etc. and save it to the variable ${name_list}