Shell script to copy and prepend folder name to files from multiple subdirectories

佐手、 提交于 2019-11-30 07:28:57

This is a bit tedious but will do:

#!/bin/bash
parent=/parent
newfolder=/newfolder
mkdir "$newfolder"
for folder in "$parent"/*; do
  if [[ -d "$folder" ]]; then
    foldername="${folder##*/}"
    for file in "$parent"/"$foldername"/*; do
      filename="${file##*/}"
      newfilename="$foldername"_"$filename"
      cp "$file" "$newfolder"/"$newfilename"
    done
  fi
done

Put the parent path to parent variable and newfolder path to newfolder variable.

I would use something like this:

find -type f -exec sh -c 'f={}; fnew=$(rev <<< "$f" | sed 's~/~_~' | rev); echo "mv $f $fnew"' \;

This looks for files within the current directory structure and perform the following:

  • get the file name
  • replace the last / with _.
  • write echo "cp $old_file $new_file"

Once you have run this and seen it prints the proper command, remove the echo so that it effectively does the mv command.

I know the fnew=$(rev <<< "$f" | sed 's~/~_~' | rev) is a bit ugly trick, but I couldn't find a better way to replace the last / with _. Maybe sed -r 's~/([^/]*)$~_\1~' could also be appropiate, but I always like using rev :)


Since your find does not behave well with the -sh c expression, let's use a while loop for it:

while read -r file
do
    new_file=$(rev <<< "$file" | sed 's~/~_~' | rev)
    echo "mv $file $new_file"; done < <(find . -type f)
done < <(find . -type f)

As a one-liner:

while read -r file; do new_file=$(rev <<< "$file" | sed 's~/~_~' | rev); echo "mv $file $new_file"; done < <(find . -type f)

functions to the rescue, updating Jahid's script:

function updateFolder
{
    mkdir "$2"
    for folder in "$1"/*; do
    if [[ -d $folder ]]; then
        foldername="${folder##*/}"
        for file in "$1"/"$foldername"/*; do
            filename="${file##*/}"
            newfilename="$foldername"_"$filename"
            cp "$file" "$2"/"$newfilename"
        done
    fi
    done
}

used:

$ updateFolder /parent /newfolder
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!