Malik
Malik

Reputation: 195

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}

Upvotes: 4

Views: 4504

Answers (4)

jorgenkg
jorgenkg

Reputation: 4275

The command:

$ tr -s '\n ' ',' < sourcefile.txt             # Replace newlines and spaces with [,]

This will likely return a , as the last character (and potentially the first). To shave of the comma(s) and return a satisfying result:

$ name_list=$(tr -s '\n ' ',' < sourcefile.txt)      # store the previous result
$ name_list=${tmp%,}                                 # shave off the last comma
$ name_list=${tmp#,}                                 # shave off any first comma


EDIT

This solution runs 44% faster and yields consistent and valid results across all Unix platforms.

# This solution
python -mtimeit -s 'import subprocess' "subprocess.call('tmp=$(tr -s "\n " "," < input.txt);echo ${tmp%,} >/dev/null',shell = True)"
100 loops, best of 3: 3.71 msec per loop

# Highest voted:
python -mtimeit -s 'import subprocess' "subprocess.call('column input.txt | sed "s/\t/,/g" >/dev/null',shell = True)"
100 loops, best of 3: 6.69 msec per loop

Upvotes: 3

perreal
perreal

Reputation: 97938

Using column, and sed:

namelist=$(column input | sed 's/\t/,/g')

Upvotes: 1

Vijay
Vijay

Reputation: 67211

variable=`perl -lne 'next if(/^\s*$/);if($a){$a.=",$_"}else{$a=$_};END{print $a}' your_file`

Upvotes: 0

blue
blue

Reputation: 2793

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

Upvotes: 3

Related Questions