creativeDev
creativeDev

Reputation: 1123

bash creating a csv file

I would like to create a csv file. The filename of the .txt file should be the header and all jpgs files inside the .txt file should be the rows.

Example:

filename1.txt, filename2.txt, filename3.txt
filename1a.jpg,filename2a.jpg,filename3a.jpg
filename1b.jpg,filename2b.jpg,filename3b.jpg
filename1c.jpg,filename2c.jpg,filename3c.jpg
              ,filename2d.jpg,

The problem I am having is how to append to file with the right format as above?

for f in $(ls *.txt) do
    csv_header="$f"
    #get all jpgs in current txt file
    array_jpgs=( $(get_jpgs "$f") )
    for jpg in "${array_jpgs[@]}" do
        #printf "%s," "$csv_header" >> "$CSV_FILE"
    done
done

I am using GNU bash, version 4.3.33

Upvotes: 0

Views: 203

Answers (1)

chepner
chepner

Reputation: 531175

Just use paste to combine a bunch of temporary files. (Assuming the output of get_jpgs is one file name per line.)

for f in *.txt; do   # Do not parse ls
    { printf '%s\n' "$f"
      get_jpgs "$f"
    } > "$f.tmp"
done
paste -d, *.tmp > "$CSV_FILE"
rm *.tmp

Upvotes: 1

Related Questions