Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .