Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Bash to create a copy of a file with an extra suffix before the extension?

Tags:

bash

file-io

This title is a little confusing, so let me break it down. Basically I have a full directory of files with various names and extensions:

MainDirectory/
    image_1.png
    foobar.jpeg
    myFile.txt

For an iPad app, I need to create copies of these with the suffix @2X appended to the end of all of these file names, before the extension - so I would end up with this:

MainDirectory/
    image_1.png
    [email protected]
    foobar.jpeg
    [email protected]
    myFile.txt
    [email protected]

Instead of changing the file names one at a time by hand, I want to create a script to take care of it for me. I currently have the following, but it does not work as expected:

#!/bin/bash

FILE_DIR=.

#if there is an argument, use that as the files directory. Otherwise, use .
if [ $# -eq 1 ]
then
  $FILE_DIR=$1
fi

for f in $FILE_DIR/*
do
  echo "Processing $f"
  filename=$(basename "$fullfile")
  extension="${filename##*.}"
  filename="${filename%.*}"
  newFileName=$(echo -n $filename; echo -n -@2X; echo -n $extension)
  echo Creating $newFileName
  cp $f newFileName
done

exit 0

I also want to keep this to pure bash, and not rely on os-specific calls. What am I doing wrong? What can I change or what code will work, in order to do what I need?

like image 239
Phil Avatar asked Oct 11 '12 16:10

Phil


1 Answers

#!/bin/sh -e 
cd "${1-.}"

for f in *; do  
  cp "$f" "${f%.*}@2x.${f##*.}"
done
like image 99
William Pursell Avatar answered Oct 14 '22 23:10

William Pursell