Rename files

2024 Nov 11 bash Skill

In this tutorial, I show a case of adding a prefix to certain file names that saves many mouse clicks. From terminal, this task seems easy, but in actual file names are some how hard to fetch.

For example, if the file name pattern spans between SRP4078…SRP4090, the numeric sequence can loop like this:

$for i in 40{78..90}; echo $i; done

To reuse this line, wrapping to a script, however, comes to an error. It stops after the first element of the range: $bash fetch_file.sh 40{78..90}

#!/bin/sh
PATTERN=$1
for i in *$PATTERN*; echo $i; done

Luckily, I found another way to match the file name pattern: $bash fetch_file.sh 407[8-9] prefix_

#!/bin/sh
PATTERN=$1
PREFIX=$2
for i in *$PATTERN*; mv $i $PREFIX$f; done

One issue left is that bash only recognizes the last digit of input pattern, and ‘[78-90]’ will be read as a character string rather than a range.