Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read line from file and save them in a comma separated string to a variable

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}

like image 767
Malik Avatar asked Sep 01 '25 10:09

Malik


1 Answers

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
like image 73
blue Avatar answered Sep 03 '25 03:09

blue