-1

Takes 2 arguments , source & destination and removes all files except txt. .Im just learning bash so not used/aware of the different functions etc...

mkdir $2
cp -R $1/* $2

for file in $1/*;do #all files in testInput
   if [ -d "$file" ] #if its a file then look at the contents of it
   then
      for inDir in $file/*; do
         if [ -d "$inDir" ]
         then
            for line in $inDir ; do
               if [ line != *.txt ]
               then
                  rm line

               fi
            done
          fi
       done

    else
       for files in file; do
          if [ files != *.txt ]
          then
             rm files
          fi
       done

    fi     
done

source is a folder which contains the 3 folders and some of these subfolder contain a subfolder and files

naab
  • 1,122
  • 1
  • 8
  • 25
stringRay2014
  • 636
  • 1
  • 11
  • 29

2 Answers2

1

Takes all files in directory $1 except *.txt files and moves them to directory $2.

find "$1" -type f ! -name "*.txt" -exec mv -v "{}" "$2" \;

As always, be careful with this...

edit added quotes around variables

edit2 quoted file name placeholder, added debug output to mv

mxm
  • 605
  • 5
  • 13
1

You should use find to do that kind of task. Here is an example :

find "$dir" -type f ! -name "*.txt" -exec rm {} \;

Otherwise :

if [ line != *.txt ]
# ...
if [ files != *.txt ]

You're missing the $ before the variable name and the test is incorrect. You could try something like this instead :

[[ $line =~ \.txt$ ]] || rm line

Moreover :

for files in file; do

You're missing the character $ before the variable name and you should use something like this instead :

for files in "$file"/*; do

Finally, you don't protect your variables properly. Read this : bash : Illegal number

Community
  • 1
  • 1
Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32
  • 1
    +1 for `=~`. Totally unused thoses days while it should. Many regex problems can be solved this way without the use of `grep` etc – naab Apr 13 '14 at 11:39
  • The `=~` operator is only available in bash >= 3. But bash >= 3 is available on all Linux versions and Mac OS X. So I also like to use this operator instead of an external program like `grep` ;) – Idriss Neumann Apr 13 '14 at 11:45
  • So how will i implement my function with find? – stringRay2014 Apr 16 '14 at 14:09