Renaming files but keeping them in their present subdirectory

78 views Asked by At

I have a script that renames html files based on information in their tags. This script goes through the current directory and all subdirectories and performs this renaming recursively. however, after renaming them it moves them into the current working directory I am executing my shell script from. How can I make sure the files remain in their subdirectories, and are not moved to the working directory?

Here is what I am working with:

#!/usr/bin/env bash
for f in `find . -type f | grep \.htm`
   do
   title=$( awk 'BEGIN{IGNORECASE=1;FS="<title>|</title>";RS=EOF} {print $2}' "$f" )
   mv  ./"$f" "${title//[ ]/-}".htm
done
3

There are 3 answers

0
John1024 On

Try:

mv  ./"$f" "$(dirname "$f")/${title//[ ]/-}".htm

Note that your for f in \find...' will fail on any file name with a space or CR in it. You can avoid that with a line like:

find . -type f -name '*.htm' -type f -exec myrename.sh {} \;

where the renaming code is in a script called myrename.sh.

0
glenn jackman On
shopt -s globstar nullglob
for f in **/*.htm
do
   title=$( awk 'BEGIN{IGNORECASE=1;FS="<title>|</title>";RS=EOF} {print $2}' "$f" )
   mv  "$f" "$(dirname "$f")/${title//[ ]/-}".htm
done
0
Ed Morton On

Never use this construct:

for f in `find . -type f | grep \.htm`

as the loop fails for file names that contain space and the grep's unnecessary as find has a -name option for that. Use this instead:

find . -type f -name '*\.htm.*' -print |
while IFS= read -r f

This:

awk 'BEGIN{IGNORECASE=1;FS="<title>|</title>";RS=EOF}

can be reduced and clarified to:

awk 'BEGIN{IGNORECASE=1;FS="</?title>";RS=""}

Note that the use of EOF was misleading as EOF is just an undefined variable which therefore contains a null string (so your first record will go until the first blank line, not until the end of the file). You could have used RS=bubba and got the same effect but just setting RS to an empty string is clearer. Not saying it's what you SHOULD be doing, but it's a clearer implementation of what you ARE doing.

Finally putting it all back together something like this should work for you:

find . -type f -name '*\.htm.*' -print |
while IFS= read -r f
do
    title=$( awk 'BEGIN{IGNORECASE=1;FS="</?title>";RS=""} {print $2}' "$f"
    mv -- "$f" $(dirname "$f")/"${title//[ ]/-}".htm
done