3

OS: Ubuntu 14.04.2 LTS (GNU/Linux 3.13.0-62-generic x86_64)

I have a directory like the following:

~/total/
    test1/
        test1.txt
        some_other_file_i_dont_care.py
    test2/
        test2.tex
        some_folder_i_dont_care/
    test3/
        test3.csv

I want to move only the text files out of there, and erase their parent folders (which have the same names as the files I'm interested in).

So the result should be this:

~/total/
    test1.txt
    test2.tex
    test3.csv

I think I'm not far from the solution with this function:

find ~/total/ -type f  \( -iname '*.txt' -o -iname '*.tex' -o -iname '*.csv' \)          
| xargs mv -ifile file ~/total/

But then, how can I remove the remaining folders?

tomasyany
  • 133
  • 3

1 Answers1

3

You can do the two operations in one go of find :

find . -depth \( -regex '.*\.\(txt\|tex\|csv\)' -exec mv -- {} . \; \
                 -o -not -name . -delete \)
  • -regex '.*\.\(txt\|tex\|csv\)' -exec mv -- {} . \; will find the files with .txt or .tex or csv extensions and will move those to the current directory

  • -not -name . -delete will then remove everything else

Example :

total$ tree
.
├── test1
│   ├── some.py
│   └── test1.txt
├── test2
│   ├── somedir
│   └── test2.tex
└── test3
    └── test3.csv


total$ find . -depth \( -regex '.*\.\(txt\|tex\|csv\)' -exec mv -- {} . \; -o -not -name . -delete \)


total$ tree
.
├── test1.txt
├── test2.tex
└── test3.csv
heemayl
  • 90,425
  • 20
  • 200
  • 267
  • Pretty nice solution. I'm accepting it. Nevertheless my solution it's not much longer and it has the advantage of being separated into two yunks of logical code. – tomasyany Sep 04 '15 at 01:14
  • @tomasyany In your answer you don't need `xargs`..`find..-exec` alone can handle unusual filenames..also it doesn't trigger ARG_MAX – heemayl Sep 04 '15 at 01:29
  • It's true that it becomes more complicated, since I hace to add a `-print0` option so it would work with files with spaces. There's still one question I have: can you put confirmation question for every directory deleted? I can't with `rm -ir` for stdin reasons, but I could do it with `for i in $(find ~/test/ -type d); do rm -ir "$i"; done` – tomasyany Sep 04 '15 at 01:39
  • 1
    @tomasyany Yes, you can..in that case use `-exec rm -ir {} \;` instead of `-delete` – heemayl Sep 04 '15 at 19:36