Issue
#!/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/
Solution
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 stringDir
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,)
Answered By - xhienne