Question

I have a lot of files (images) like this (file names consist only from numbers):

123456.jpg
369258.jpg
987123.jpg
...

I need to make a copy of each in some other folder (let's name it output) and rename each of the file based on numbers in their name, something like this (in pseudocode):

outputFileName = String(filename[0]) + String(filename[1]) + String(filename[2]+filename[3]) + ".jpg"

So as you can see, the renaming involves getting a certain symbol in file name and sometimes getting a sum of some symbols in file name.

I need to make a script to mass rename all *.jpg in the folder where I put the script based on similar algorithm, and output renamed ones in output folder I mentioned earlier.

This script should be workable from macos terminal and windows via cygwin shell.

Was it helpful?

Solution

I assume main problems are: how to get particular character of bash variable and how to perform addition in bash.

  1. To obtain a char from bash variable you can use this form: ${var:START_INDEX:LENGTH}.

  2. To perform addition: $((ARG1 + ARG2))

Your resulting script may be like that:

#!/bin/bash

for f in *.jpg
do
  output=${f:0:1}${f:1:1}$((${f:2:1} + ${f:3:1})).jpg
  mv -- "$f" "$output"
done

OTHER TIPS

You are looking for substring extraction.

The syntax is ${string:position:length}, where string is the name of the variable, position is the starting position (0 is the first index), and length is the length of the substring.

A script that would create the filenames as specified in the question, and copy them for a folder named "input" to a folder named "output" could look like this:

#!/bin/bash
for file in input/*.jpg
do
    filename="$(basename "$file")"
    firstChar="${filename:0:1}"
    secondChar="${filename:1:1}"
    thirdAndFourthChar="$(( ${filename:2:1} + ${filename:3:1} ))"
    newfilename="$firstChar$secondChar$thirdAndFourthChar.jpg"
    cp "$file" "output/$newfilename"
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top