Rename file in bourne shell

I'm trying to write a bourne-shell script that takes a directory as a parameter and looks for images named ixxx.a and renames them to ixxx_a.img where "xxx means the extension number for example image files will be named i001.a, i002.a, i003 .a ...) here is what I tried

mv $1/f[0-9][0-9][0-9].a $1/f[0-9][0-9][0-9]_a.img


but he says DEST is not a directory. Any help is appreciated. Thank.


source to share

1 answer

for i in $1/f[0-9][0-9][0-9].a; do
  mv $i ${i%.a}_a.img


However, this does not consider spaces in file / folder names. In this case, you would need to use while

to get you one filename per line (see bonus below). There are probably dozens of other ways, including rename


find $1 -maxdepth 1 -type f -name "f[0-9][0-9][0-9].a"|while read i; do
  mv "$i" "${i%.a}_a.img"


Edit: Perhaps I should explain what I did there. It's called string substitution, and the main uses are for variables var


# Get first two characters
# Remove shortest rear-anchored pattern - this one would give the directory name of a file, for example
# Remove longest rear-anchored pattern
# Remove shortest front-anchored pattern - this  in particular removes a leading slash
# Remove longest front-anchored pattern - this would remove all but the base name of a file given its path
# Replace a by b


See page for details man




All Articles