Reputation: 393
#!/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
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:
Dir+="Dir,$line"
, the string Dir
should probably be removed (Dir+=",$line"
).Dir=${Dir#,}
.Dir=$(paste -s -d, dir.csv)
... or, with CRLF line-endings:
Dir=$(tr -d '\r' < dir.csv | paste -s -d,)
Upvotes: 4
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