LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash script to copy rename files (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-to-copy-rename-files-4175431076/)

dunstable 10-08-2012 03:46 AM

bash script to copy rename files
 
Hi I am trying to right a bash script that will scan folders recursivly for file types .tbn and copy that file and rename it to cover.jpg within same directory.
So far the following script finds files but copys and renames file to where i run the cript from not where the original file is.
Not understanding the the basic syntax is a big handicap have done extensive searches but cant quite find what i am looking for.


for file in **/*.tbn
do
cp "${file}" cover.jpg
done

asimba 10-08-2012 03:53 AM

I think something following should do the trick


find ./ -name <filename.extension> | xargs mv <suit your needs>

colucix 10-08-2012 04:05 AM

Code:

cp "${file}" cover.jpg
Since you didn't specify a path for cover.jpg, it will be copied/renamed in the current working directory. If you want to copy the file in the same directory where the original is, you have to extract the path from the matched file name: Example:
Code:

#!/bin/bash
#
shopt -s globstar

for file in **/*.tbn
do
  cp "$file" "$(dirname "$file")"/cover.jpg
done

Instead, using the find command, as suggested by asimba, the -execdir predicate accomplishes the task for you, that is it executes the command from inside the directory where the file is, so that
Code:

find . -name \*.tbn -execdir cp {} cover.jpg \;
should do the trick.

dunstable 10-08-2012 04:29 AM

Many thanks

Quote:

Originally Posted by colucix (Post 4800030)
Code:

cp "${file}" cover.jpg
Since you didn't specify a path for cover.jpg, it will be copied/renamed in the current working directory. If you want to copy the file in the same directory where the original is, you have to extract the path from the matched file name: Example:
Code:

Code:

#!/bin/bash
#
shopt -s globstar

for file in **/*.tbn
do
  cp "$file" "$(dirname "$file")"/cover.jpg
done


Did the Trick
Thank you all for your fast replies this bugging me for 3 hours

David the H. 10-08-2012 10:53 AM

No need for dirname, an external command. Just use built-in parameter substitution.

Code:

cp "$file" "${file%/*}"/cover.jpg
You might also consider using the -t option instead with cp/mv in this kind of scripting situation.

I think the find version used above is a better choice though.


All times are GMT -5. The time now is 05:29 AM.