Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

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
share|improve this answer
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
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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