2

So far I have come up with this.

if ls -1 ~/Downloads/*.mkv >/dev/null 2>&1
then
        echo 1
else
        echo 0
fi

But what I would like to do is to then copy the parent dir of the found file to another location.

I have a feeling that I should just use the find command.

2
  • Can you please describe what you really need to accomplish? If a folder contains a .mkv you want to copy the folder somewhere else?
    – slhck
    Dec 4, 2013 at 8:30
  • @slhck Yes, that is what I would like to do. Dec 4, 2013 at 8:34

2 Answers 2

2

fede.evol's answer fails if paths contain whitespace. The output of find or ls shouldn't be used in a command substitution.

The proper way to deal with all filenames (except for paths with newlines) would be:

find /somewhere -name "*.mkv" -exec dirname {} \; | uniq | \
while IFS= read -r dir; do echo cp -- "$dir" /other/; done

This way, each folder from /somewhere is copied to /other/. Note that the trailing slash is mandatory, because otherwise the target would always be overwritten.

1

Use dirname FILE to get the directory name of a given file. So for example:

find DIRECTORY -name "*.mkv" -exec dirname {} \;

Will give you all the directories with an MKV under DIRECTORY. Then you can pass them through uniq not to get doubles and then in case copy.

For example

cp -a `find DIRECTORY -name "*.mkv" -exec dirname {} \; | uniq` DESTDIR
1
  • Your last command will fail if the directory path contains spaces. You should not use command substitution on find or ls output.
    – slhck
    Dec 5, 2013 at 21:24

You must log in to answer this question.

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