1

I am generating 2 output file from input wile using shell script. One successfully creating but 2nd file having only one row .

Suppose I have one input file(csv) with 3 rows.It generate one output file with some other information with all 3 rows But 2 nd out put file only generating with some other value with 1 row value only . Here Is my code :

#! /bin/bash
SAVEIFS=$IFS
IFS=","
if [ $# -gt 0 ]; then
    INPUT_FILE="$1" 
    echo 'Brand,Width (mm),Height (mm),Depth (mm)' > mug.csv 
    echo 'Design Name, Type,Product ' > mugsku.csv 
    while read Brand designname width height types 
    do  
        echo "$brand.$width,$height,$depth" >> mug.csv
        echo "$designname,$types,$ptype" > mugsku.csv 
    done < $INPUT_FILE
else
    echo "No argument passed.Pass valid file name"
fi

Input file name I am passing as an argument

Inian
  • 80,270
  • 14
  • 142
  • 161
Urvashi
  • 239
  • 2
  • 10

1 Answers1

1

It is because of the below line, which over-writes (> operator) the file on every iteration of the for-loop.

echo "$designname,$types,$ptype" > mugsku.csv 

You should have been using the append operator(>>) like,

echo "$designname,$types,$ptype" >> mugsku.csv

You can do a few-more optimizations over your script,

  1. Double-quote your variables, e.g. as "$INPUT_FILE"
  2. Add a -r flag to read to make it more robust.
Inian
  • 80,270
  • 14
  • 142
  • 161
  • Please help me in one more thing.I am reading csv file it reads only 2 instead of three.It read 3rd line if i give enter in last row in input file.Can you please tell me what will be the reason for this. – Urvashi Jan 12 '17 at 09:13
  • @Urvashi: Can you explain it a bit more? I can't understand it clearly – Inian Jan 12 '17 at 09:20
  • Got solution from http://stackoverflow.com/questions/20010741/why-does-unix-while-read-not-read-last-line.Thanks you very much once again – Urvashi Jan 12 '17 at 09:21