Issue
I have several folders inside a directory called freesurfer like:
freesurfer/sub-001/mri
freesurfer/sub-001/label
freesurfer/sub-001/surf
freesurfer/sub-001/stats
freesurfer/sub-002/mri
freesurfer/sub-002/label
freesurfer/sub-002/surf
freesurfer/sub-002/stats
I would like to rename only 'stats' folder and move it to a different location:
freesurfer/sub-001/mri
freesurfer/sub-001/label
freesurfer/sub-001/surf
freesurfer/sub-001/sub-001_stats
freesurfer/sub-002/mri
freesurfer/sub-002/label
freesurfer/sub-002/surf
freesurfer/sub-002/sub-002_stats
I have managed to write the following code:
while read dir ; do
new_dir=$(rev <<< "$dir" | sed 's~/~_~' | rev);
echo "mv $dir $new_dir";
done < <(find . -type d -name 'stats')
The above code seems to be working fine when I run it with 'echo' before 'mv' command and appends the folder name in front of 'stats' directory but when I take the 'echo' off, it gives an error saying: "No such file or directory". What am I doing wrong?
Solution
Your code to create new_dir
isn't correct. It's creating freesurfer/sub-002_stats
instead of freesurfer/sub-002/sub-002_stats
. But this doesn't explain the error you're getting, since it will just rename the file incorrectly (moving all of them into the parent directory).
Try:
while read dir ; do
new_dir=$(dirname "$dir")/$(basename $(dirname "$dir"))_stats
mv "$dir" "$new_dir"
done < <(find . -type d -name 'stats')
Answered By - Barmar Answer Checked By - Mildred Charles (WPSolving Admin)