John Lexus
John Lexus

Reputation: 3636

Saving file name as an incrementing number

I'm trying to write a bash script that would save a screenshot of a file I take in a specific format. I want it to be saved as a number (say, 0001.jpeg) and if 0001.jpeg already exists, then go ahead and save it as 0002.jpeg, and so on. I know that with ffmpeg, when trying to save a frame from a video you can have the format of how it saves like this: /path/to/place/%04d.ext and it would do just what I want it. I tried that with my code so that it looks like this:

gnome-screenshot -w -B -f /home/usr/ws/images_to_process/$%04d.jpeg

I also tried:

gnome-screenshot -w -B -f /home/usr/ws/images_to_process/$(%04d).jpeg

and:

gnome-screenshot -w -B -f /home/usr/ws/images_to_process/%04d.jpeg

but that didn't work. As you can see, I can't think of much variability. Does anyone know how to do it?

Thanks

Upvotes: 2

Views: 578

Answers (1)

A.Villegas
A.Villegas

Reputation: 517

You are using the correct number format to generate the outfile name, but you need a variable and a printf to translate the "/home/usr/ws/images_to_process/%04d.jpeg" to "/home/usr/ws/images_to_process/0001.jpeg"

I made a little script that creates the files using a serial number without overwrite the already existing files.

  #!/bin/bash

  FILENAME="file_%04d.txt"
  COUNTER=0

  #Change true for your finish condition
  while true; do
        target=$(printf $FILENAME $COUNTER)

        # If not exists file $tarjet
        # -f check if exist a file
        # ! not condition
        if [ ! -f $target ]; then
              touch $target
        fi
        # counter ++
        COUNTER=$(($COUNTER + 1))
  done

You can change the "touch $target" for "gnome-screenshot -w -B -f $target" and the variable "target" for you outfile name. The result script is:

  #!/bin/bash

  FILENAME="/home/usr/ws/images_to_process/%04d.jpeg"
  COUNTER=0

  while true; do
        target=$(printf $FILENAME $COUNTER)
        if [ ! -f $target ]; then 
              gnome-screenshot -w -B -f $target
        fi
        COUNTER=$(($COUNTER + 1))
  done

I hope that info was usefull.

Upvotes: 2

Related Questions