Balan
Balan

Reputation: 393

Read input from a csv and append that values to variable using shell script

#!/bin/bash

Dir="" 
while read line
    do echo "Record is :$line"
    Dir+="Dir,$line" 
done < dir.csv 

echo $Dir

where dir.csv is an input file here which includes following data:

/example/people/
/book/
/book/english/

I would like to append the values of the rows into one variable like /example/people/,/book/,/book/english/

Is there any easy way to achieve this through shell script? above script is showing only the last value ex:/book/english/

Upvotes: 1

Views: 953

Answers (2)

xhienne
xhienne

Reputation: 6134

I don't see anything in your code that would cause your script to only show the last value.

This may be an illusion: is your dir.csv file CRLF-delimited? (DOS/Windows format) If so, remove the CR that ends each line with a utility like dos2unix or a command like tr -d '\r'.

Some notes though:

  • In Dir+="Dir,$line", the string Dir should probably be removed (Dir+=",$line").
  • You probably want to get rid off the initial comma: Dir=${Dir#,}.
  • All this can be simplified with the single command below:
Dir=$(paste -s -d, dir.csv)

... or, with CRLF line-endings:

Dir=$(tr -d '\r' < dir.csv | paste -s -d,)

Upvotes: 4

Ron
Ron

Reputation: 6591

This is easier:

xargs < dir.csv|sed 's/ /,/g'

or if you have CRLF line endings, you can clean those up with:

xargs < dir.csv|tr -d '\r'|sed 's/ /,/g'

The above proposed tr '\n' ',' < dir.csv can add an additional , at the end if the CSV ends with newline

Upvotes: 1

Related Questions