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" \;
Related videos on Youtube
Author by
Arjun
Updated on September 18, 2022Comments
-
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 about 8 yearsHow do you handle the case where the
grep
finds nothing? -
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 about 8 yearsTo clarify that, you should echo the
cd
command. -
thrig about 8 yearsOkay, but when
grep
finds nothing, the resultingcp $1
command then lacks a destination file, causing the error message. Are you sure that's fine? -
Arjun about 8 years@thrig I guess it is better to handle it then. Thanks for the heads up.
-
-
Arjun about 8 yearsThanks! Yes, as mentioned above in the comments, I think it is better to handle a situation with empty directories.