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?


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.

  • You probably need to limit the depth of the search, otherwise the copy will fail for subdirectories – nohillside Oct 10 '17 at 12:30
  • @patrix, What!? If I understood the OP this does exactly what was asked as is, no need to limit find's depth as it's supposed to find all info.txt files in the subdirectories of the PWD. – user3439894 Oct 10 '17 at 12:34
  • Yeah, whatever. If the OP is happy, fine :-) – nohillside Oct 10 '17 at 12:48
  • @patrix, I've updated my answer to address your comment. – user3439894 Oct 10 '17 at 12:59

Assuming somewhat sane directory names (no newlines etc.)

ls | while read dir; do
    [[ -e "$dir"/info.txt ]] && cp ../y/info.txt "$dir"/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .