Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I want to write a simple shell script that will go into all the sub-folders in a directory, and organise the files in the sub-folders into new directories. Basically in terminal it would look like:

cd ../subfolder1
mkdir newfolder
mv *.txt newfolder
cd ../subfolder2
mkdir newfolder
mv *.txt newfolder
etc.

However, the cd command doesn't seem to work for the shell script. Anyone know how I could do this? Thanks a million!

share|improve this question
1  
Please explain - why do you say that cd doesn't work for shell scripts? Of course it does... –  Rmano Apr 22 at 0:59
    
Welcome to Ask Ubuntu. Please, could you put some of your time to read What should I do when someone answers my question? –  Sylvain Pineau Apr 23 at 7:24

1 Answer 1

If your directory structure is as follow:

├── subfolder1
│   ├── foo.txt
│   └── bar.other
└── subfolder2
    ├── foo2.txt
    └── baz.old

Running the following command:

find . -maxdepth 1 ! -path . -type d -exec sh -c "mkdir {}/newfolder && mv {}/*.txt {}/newfolder" \;

Will create the below tree structure:

├── subfolder1
│   ├── newfolder
│   │   └── foo.txt
│   ├── bar.other
└── subfolder2
    ├── newfolder
    │   └── foo2.txt
    ├── baz.old
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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