abc.dat file contains lines
1
2
3
code is
tradeline=""
for line in $(cat abc.dat)
do
tradeline="$line,$tradeline"
done
sample output am getting is 1,2,3, but i want the output as "1","2","3",
can u help me plz
abc.dat file contains lines
1
2
3
code is
tradeline=""
for line in $(cat abc.dat)
do
tradeline="$line,$tradeline"
done
sample output am getting is 1,2,3, but i want the output as "1","2","3",
can u help me plz
Your code has a number of problems, the first being what you describe.
It will also put the numbers in reverse order and have a trailing comma, which is probably not what you want.
If that is what you want, just use the second solution.
Solution 1, right order and no trailing comma:
tradeline=""
sep=""
for line in $(cat abc.dat) ; do
tradeline="${tradeline}${sep}\"${line}\""
sep=","
done
echo ${tradeline}
Solution 2, right order with trailing comma:
tradeline=""
for line in $(cat abc.dat) ; do
tradeline="${tradeline}\"${line}\","
done
echo ${tradeline}
Solution 3, much simpler, using tools meant for the job:
awk 'BEGIN {sep=""} {printf "%s\"%s\"",sep,$0;sep=","} END {print}' abc.dat
Solution 3 would be my preferred option since it'll be faster and be able to handle input lines with white space in them.
Note that using cat
like that will mean that if you have several words on one line, you will still quote each word separately. Also, your code will generate '3,2,1' rather than '1,2,3'.
To get quotes around each line, you would need to use the read
command:
tradeline=""
sep=""
cat abc.dat |
while read line
do
tradeline="$tradeline$sep\"$line\""
sep=","
done
This is quite similar to Pax's solution - except for the use of read
to obtain each line.