Bash Scripting – Copy File in Many Folders Only If It Exists

bashterminal

In another forum I saw this command:

ls -1 | xargs -n 1 cp ../y/info.txt

It copies info.txt into sub folders (e.g. folder a, folder b, folder c) in the current working directory.

Now I want to copy the file info.txt to sub folders replacing existing info.txt files, but do nothing when the sub folder doesn't contain info.txt.

So I need the opposite of -n.

How can I accomplish this?

Best Answer

I would not parse the output of ls, use the find command instead:

find . -type f -name "info.txt" -exec cp -v ../y/info.txt {} \;

Note that the -v option with cp isn't necessary, I just like to see what's being copied where.

To address a comment, the find command shown above searches the entire PWD. If you want to limit the the search to just first level subdirectories of the PWD then add -maxdepth 2 to the find command, e.g.:

find . -maxdepth 2 -type f -name "info.txt" -exec cp -v ../y/info.txt {} \;

In this scenario:

.
├── a
│   ├── 1
│   │   └── info.txt
│   └── info.txt
├── b
│   └── info.txt
└── c

Only ./a/info.txt and ./b/info.txt are replaced, ./a/1/info.txt is not.