2

I am writing a simple script which will take a keyword. Then, it will look for files in the directory which contain that keyword and copy them to another directory (name of directory = keyword).

The keyword is passed as a command line argument. Here's my script:

#!/bin/bash
# start

mkdir $1
cp `grep -Ril \"$1\"` $1

I seem to have an error with the cp command saying:

missing destination file operand

How can I correct this error?

Thanks!

  • How do you handle the case where the grep finds nothing? – thrig Jun 7 '16 at 15:41
  • @thrig That's fine. The number of keywords are very limited actually. Around 4-5. So, in such a case, I expect to end up with empty directories. – Arjun Jun 7 '16 at 15:42
  • To clarify that, you should echo the cd command. – Julie Pelletier Jun 7 '16 at 15:50
  • Okay, but when grep finds nothing, the resulting cp $1 command then lacks a destination file, causing the error message. Are you sure that's fine? – thrig Jun 7 '16 at 16:07
  • @thrig I guess it is better to handle it then. Thanks for the heads up. – Arjun Jun 7 '16 at 18:31
4

The solution in Mike's answer is mostly correct, however I would change it slightly to create the directory only if grep finds something thus preventing the empty directories

#!/bin/bash
filenames=$(grep -Ril "$1")
[ $? -eq 0 ] && mkdir "$1"
for file in $filenames; do
    cp "$file" "$1"
done
  • Thanks! Yes, as mentioned above in the comments, I think it is better to handle a situation with empty directories. – Arjun Jun 7 '16 at 18:33
2

This is the correct way:

#!/bin/bash
mkdir "$1"
filenames=$(grep -Ril "$1")
if [ $? -eq 0 ] ; then
    echo "$filenames" | while IFS= read -r line ; do
        cp "$line" "$1"
    done
fi
1

You could try to use find :

mkdir "$1"
find . -type f -name "*$1*" -exec cp {} path/to/"$1" \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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