0

I want to copy files of the given type with inside subdirectories. I think copy of the zzz.txt file works after copying the files in the abc_folder. How can i resolve this problem.

AAA
   ---aaa.txt
   ---bbb.txt
   ---zzz.txt
   ---abc_folder
                ---aaa.txt
                ---bbb.txt
                ---ccc.txt

Wanted output

    AAA
   ---aaa.txt
   ---bbb.txt
   ---zzz.txt
   ---1.txt
   ---2.txt
   ---3.txt
   ---abc_folder
                ---aaa.txt
                ---bbb.txt
                ---ccc.txt
                ---1.txt
                ---2.txt
                ---3.txt

My code's output

        AAA
   ---aaa.txt
   ---bbb.txt
   ---zzz.txt
   ---1.txt
   ---2.txt
   ---4.txt
   ---abc_folder
                ---aaa.txt
                ---bbb.txt
                ---ccc.txt
                ---1.txt
                ---2.txt
                ---3.txt

My code

#!/bin/bash

function traverse() {
counter=1
for file in "$2"/*
do
  if [ ! -d "${file}" ]; then
      if [[ $file == $3 ]]; then
          extension="${file##*.}"
          filename="${file%.*}"
          cp "$file" "${2}/${counter}.${extension}"
          counter=$(($counter + 1))
      fi
  elif [ $1 == "-R" ] ; then
      traverse "${1}" "${file}" "${3}"
  fi
done
}
traverse "$1" "$PWD" "$2"
0

With zsh:

#! /bin/zsh -
autoload zmv
incr='++count[$1]'
typeset -A count
zmv -n '(**/)(*)(.txt)' '$1$((incr))$3'

(remove -n when happy)

The idea being to use an associative arrays whose key is the directory for counting.

We need the intermediary incr variable or otherwise it wouldn't work for directory names containing ].

  • I want to use just pure bash – zblash Apr 14 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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