LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Script to change the extension in folders (https://www.linuxquestions.org/questions/programming-9/script-to-change-the-extension-in-folders-913318/)

lee_can 11-13-2011 11:04 AM

Script to change the extension in folders
 
Hi,
i want to write a script to change the extension of a file to new extension.

i already wrote a script which i can change all the files in one folder, but the thing that i have more then 300 folders, and i want to go to each folder and run the script.
is there a way, to run the script, so it can go to each folder and change the extension.
for example, the main folder is "main" located in /root/home/main
in main folder, i have the folders: f1, f2, f3, ..., f100.
the files located in "f1, f2, ..." are like this: "1.txt;1", "2.tta;1", etc,,
the extension is ".txt;1", "tta;1".
so, my script is:

Code:

#!/bin/bash
for name in `ls -1 | grep -v $0`
do
        file_ext_1=`echo $name |cut -d';' -f1`
        mv $name $file_ext_1
done

how can i change this script to start by itself going to each folder and change the ext, but i just need to to do this only on "main" and its folders.

Thanks in advance.
regards

unSpawn 11-13-2011 11:56 AM

Please be aware of
0) proper quoting,
1) the difference between "for" and "while" loops,
2) problems due to spaces in file names and
3) using the wrong tool for the right job (like using 'ls' instead of 'find'):

Code:

find /root/home/main -type f -iname "*.txt;*" | while read ITEM; do
 NEWNAME="${ITEM//;1/}"; echo mv "${ITEM}" "${NEWNAME}"
done


Code:

function help() { echo "Bash scripting guides:
http://www.tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html
http://www.tldp.org/LDP/Bash-Beginners-Guide/html/index.html
http://www.gnu.org/software/bash/manual/html_node/index.html
http://www.grymoire.com/Unix/Sh.html
http://www.tldp.org/LDP/abs/html/
http://wooledge.org/mywiki/BashFAQ?action=show&redirect=BashFaq
http://wooledge.org/mywiki/BashPitfalls"; }


grail 11-13-2011 06:25 PM

I am surprised the original script worked at all as a semi colon is deemed the end of the previous command.
A slight edit you can do on unSpawn's script is:
Code:

NEWNAME="${ITEM//;1/}"

NEWNAME="${ITEM%;1}"

Not sure there is any advantage of one over the other.

lee_can 11-14-2011 10:02 AM

[QUOTE=unSpawn;4523007]Please be aware of
0) proper quoting,
1) the difference between "for" and "while" loops,
2) problems due to spaces in file names and
3) using the wrong tool for the right job (like using 'ls' instead of 'find'):

Code:

find /root/home/main -type f -iname "*.txt;*" | while read ITEM; do
 NEWNAME="${ITEM//;1/}"; echo mv "${ITEM}" "${NEWNAME}"
done


Very big thanks for you, i really appreciate your help, it save me lot of time.
and also thanks for the advise.

Regards


All times are GMT -5. The time now is 04:45 AM.