raptor0102 February 2016

Renaming directories at multiple levels using find from bash

I'm looping over the results of find, and I'm changing every one of those folders, so my problem is that when I encounter: /aaaa/logs/ and after that: /aaaa/logs/bbb/logs, when I try to mv /aaaa/logs/bbb/logs /aaaa/log/bbb/log it can't find the folder because it has already been renamed. That is, the output from find may report that the name is /aaaa/logs/bbb/logs, when the script previously moved output to /aaaa/log/bbb/. Simple code:

#!/bin/bash
script_log="/myPath"
echo "Info" > $script_log
search_names_folders=`find /home/ -type d -name "logs*"`
while read -r line; do
      mv $line ${line//logs/log} >>$script_log 2>&1
done <<< "$search_names_folders"

My Solution is:

#!/bin/bash
script_log="/myPath"
echo "Info" > $script_log
search_names_folders=`find /home/ -type d -name "logs*"`
while read -r line; do
      number_of_occurrences=$(grep -o "logs" <<< "$line" | wc -l)
  if [ "$number_of_occurrences" != "1" ]; then
       real_path=${line//logs/log} ## get the full path, the suffix will be incorrect
       real_path=${real_path%/*} ## get the prefix until the last /
       suffix=${line##*/} ## get the real suffix
       line=$real_path/$suffix ## add the full correct path to line
       mv $line ${line//logs/log} >>$script_log 2>&1
  fi 
done <<< "$search_names_folders"

But its bad idea, Has anyone have other solutions? Thanks!

Answers


Barmar February 2016

Use the -depth option to find. This makes it process directory contents before it processes the directory itself.

Post Status

Asked in February 2016
Viewed 1,591 times
Voted 7
Answered 1 times

Search




Leave an answer