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.

0


source to share


1 answer


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

      

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"
done

      



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
${var:0:2}
# Remove shortest rear-anchored pattern - this one would give the directory name of a file, for example
${var%/*}
# Remove longest rear-anchored pattern
${var%%/*}
# Remove shortest front-anchored pattern - this  in particular removes a leading slash
${var#/}
# Remove longest front-anchored pattern - this would remove all but the base name of a file given its path
# Replace a by b
${var//a/b}
${var##*/}

      

See page for details man

.

+1


source







All Articles