Search code examples
shellunixgrepcd

Move the entire folder into new directory if it contains a file


I have a directory

test2 with following contents :

file1
  test.pdb
  xyz.txt
  1.txt

file2
  test.pdb
  xyz.txt

file3
  test.pdb
  xyz.txt 
  1.txt

I want to move the folder(here, file 1 and file 3) which contain 1.txt to a new directory named 'complete'.How to do it?

Desired output :

complete

file1
  test.pdb
  xyz.txt
  1.txt

file3
  test.pdb
  xyz.txt 
  1.txt

test2

file2
  test.pdb
  xyz.txt

Code till now :

find . -maxdepth 2 -name "*ionized.pdb" -print| sed "s|^\./||"

Solution

  • Assuming you're using bash you can use this command from parent directory of test2/:

    while IFS= read -rd '' d; do
       [[ -f $d/1.txt ]] && echo mv "$d" complete
    done < <(find test2 -type d -print0)
    

    Once satisfied with output, you can remove echo before mv in above command.

    If not using bash then use this pipeline:

    find test2 -type d -print0 |
    while IFS= read -rd '' d; do [ -f "$d/1.txt" ] && echo mv "$d" complete; done
    

    This assumes both directories test2 and complete are at same level.