Search code examples
bashtextoutputmultipleoutputs

Combining multiple outputs from a loop into one text file with commas in Bash


I am testing out a method of motion detection using bash script. I am running an ImageMagick compare command and outputting the result into a text file.

A loop creates one output every time it runs through. I want each output to be placed into a single text file and to be separated by commas.

The code I am using is currently:

for (( x=1; x<=$vidLength; x++))
do

#Compare current frame with previous, saving result as "difference-current"png
compare -metric RMSE -fuzz 5% previous-001.png current-001.png difference+%x+.png 2>> motionData.txt    

Done

This code does proceed to put all of the data into one text file, but the data is displayed together, and just looks like one big number.

At the moment the data is put into the text file, however it is displayed like: "4873343460936622743393154537"

When I want it to read: "4873,343,4609,366,2274,339,315,4537"


Solution

  • You could do this:

    for (( x=1; x<=vidLength; x++)) # no need for $ here
    do
        #Compare current frame with previous, saving result as "difference-current"png
        compare -metric RMSE -fuzz 5% previous-001.png current-001.png difference+%x+.png 2>> motionData.txt
        if (( x<vidLength )) 
        then 
            printf , >> motionData.txt
        fi
    done
    

    printf adds a comma between each output of compare in the loop. The condition prevents a comma being added on the last iteration.