Rename files

2024 Nov 11 bash Skill

In this post, I will show an example of adding a prefix to certain file names. Other than many clicks, this task can be done in command line to fetch file name pattern.

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, here is 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

Of note that bash only recognizes the last digit of input pattern, and ‘[78-90]’ will be read as a character string rather than a range. So, the final pattern is a set of name ranges, ‘{*7[8-9]*,*8[0-9]*,*90*}’.