Kishore
Kishore

Reputation: 15

Unix shell scripting - Copy files alone from parent and sub-folders into a new folder

I have a parent folder with files and many sub-folders with files. I need to copy files alone from parent and sub-folders to an OutputFolder. Below is the folder structure.

ParentFolder: Parent_1.txt, Parent_2.txt
SubFolder1: Folder1_1.txt, Folder1_2.txt
SubFolder2: Folder2_1.txt, Folder2_2.txt

OutputFolder: Parent_1.txt, Parent_2.txt, Folder1_1.txt, Folder1_2.txt, Folder2_1.txt, Folder2_2.txt

I tried below code, but it copies all the files from sub-folders to parent folder and then move to an OutputFolder. Also, when I call "sh Filename.sh", I get missing argument to `-exec' cp: cannot stat '20190105'$'\r''/*': No such file or directory.

Today=$(date +%Y%m%d -d "today")
mkdir $Today
Yesterday=$(date +%Y%m%d -d "yesterday")
find $Yesterday -iname "*.txt" -exec cp {} $Yesterday \;
cp $Yesterday/* $Today/

Request your help on this!

Upvotes: 1

Views: 51

Answers (2)

Würgspaß
Würgspaß

Reputation: 4820

Use this:

find . -maxdepth 1 -iname "*.txt" -exec cp "{}" $Yesterday \;

to limit the depth to current directory. Mind the quotation marks around curly brackets.

Upvotes: 0

Armali
Armali

Reputation: 19375

I need to copy files alone from parent and sub-folders to an OutputFolder.

I tried below code, but it copies all the files from sub-folders to parent folder

In order to copy the files directly to the OutputFolder $Today, just specify $Today rather than $Yesterday after -exec cp {}.

I get missing argument to `-exec' cp: cannot stat '20190105'$'\r''/*': No such file or directory.

The \r is a sign of Windows line endings in your script - remove the CRs or save it in Unix format.

Upvotes: 0

Related Questions