Copy command with command line arguments

5,566

Solution 1

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

Solution 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

Solution 3

You could try to use find :

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

Related videos on Youtube

Arjun
Author by

Arjun

Updated on September 18, 2022

Comments

  • Arjun
    Arjun almost 2 years

    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!

    • thrig
      thrig about 8 years
      How do you handle the case where the grep finds nothing?
    • Arjun
      Arjun about 8 years
      @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.
    • Julie Pelletier
      Julie Pelletier about 8 years
      To clarify that, you should echo the cd command.
    • thrig
      thrig about 8 years
      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?
    • Arjun
      Arjun about 8 years
      @thrig I guess it is better to handle it then. Thanks for the heads up.
  • Arjun
    Arjun about 8 years
    Thanks! Yes, as mentioned above in the comments, I think it is better to handle a situation with empty directories.