5

I have a couple of files, let's say map-0.jpg (newest), map-1.jpg, map-2.jpg, ..., map-9.jpg (oldest). Now my cronjob downloads a new picture from the internet and should save it as map-0.jpg. All other files, however, should be newly enumerated (0 -> 1, 1 -> 2, and so on). Number 9, in my case, can be discarded.

Is there a handy bash-command that enumerates my files similar as logrotate does?

Thanks for help!

An Dorfer
  • 1,178

2 Answers2

5

you can use logrotate with some restrictions.

create a rotatemap.conf:

/path/to/map.jpg {
  rotate 9
}

then run logrotate from your cronjob like this:

logrotate -f -s /path.to/rotatemap.state /path/to/rotatemap.conf

this will rename the file map.jpg to map.jpg.1 and will delete the old map.jpg.9 if it exists.

the restrictions:

  • just about every path has to be hardcoded.
  • the number in the rotated files are always at the end of the filename. at least i found no way to change this.

read the fine manual of logrotate (man logrotate) for more information.

Lesmana
  • 20,621
0
myrotate() {
    # usage: myrotate /path/to/map-0.jpg
    local dest=$1
    local dest_dir=$(dirname "$dest")
    local dest_prefix=$(basename "${dest%-*}")
    local dest_ext=${dest##*.}
    local n

    printf "%s\n" "$dest_dir/${dest_prefix}"-*."$dest_ext" | 
    sort -V -r | 
    while IFS= read -r file; do
        n=${file##*-}
        n=${n%.*}
        echo mv "$file" "$dest_dir/${dest_prefix}-$((n+1)).$dest_ext"
    done
}

Change "echo mv" to "mv" if you're satisfied it's working.


I missed the bit where you only want to keep 9. Here's some terse bash:

for i in {8..0}; do mv map-$i.jpg map-$((i+1)).jpg; done
mv $file map-0.jpg
glenn jackman
  • 27,524