I want to rename files in multiple subfolders with a prefix (e.g., rename "file.tif" with "prefix_file.tif") and not have to be in the subfolder.

code: for f in /path/to/*; do echo mv "$f" "PRE_$f"; done

gives you this: mv /path/to/file1 PRE_/path/to/file1

instead I want this: mv /path/to/file1 /path/to/PRE_file1

any ideas?

link|improve this question
feedback

3 Answers

prefix="prefix_"
for file in /path/to/*; do
    dir=$(dirname "$file")
    base=$(basename "$file")
    dest="$dir"/"$prefix""$base"
    echo mv "$file" "$dest"  # remove "echo" after testing
done
link|improve this answer
feedback

Using Bash:

for f in /path/to/*
do 
    dir="${f%/*}"
    echo mv "$f" "$dir/PRE_${f/$a\/}"
done

All on one line:

for f in /path/to/*; do dir="${f%/*}"; echo mv "$f" "$dir/PRE_${f/$a\/}"; done
link|improve this answer
feedback

The first command by Mike worked. I write it here in one line:

for f in /path/to/*; do dir=$(dirname "$f"); base=$(basename "$f"); dest="$dir"/"$prefix""$base"; echo mv "$f" "$dest"; done

The second command by Dennis seemed to have the wrong output: path/prefix_path/filename instead of path/prefix_filename

It could be that it has to do with the fact that my folder names have a space in them?

oops, here is the correct one line:

prefix="prefix_"; for f in /path/to/*; do dir=$(dirname "$f"); base=$(basename "$f"); dest="$dir"/"$prefix""$base"; echo mv "$f" "$dest"; done

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.