Skip to main content

Find files based on directory prefix name and copy to directory [Resolved]


Can someone please show the simplest way to do this in a shell script.

I have the following list containing directory names:

head -3 list.txt


For each entry in the list.txt cd into existing directory:

cd 271_Lsasrv_dll_MS04-011/

Take the prefix number and search in /usr/share/exploitdb/ path

find /usr/share/exploitdb/ -name  271.*

Copy the file to existing directory

cp /usr/share/exploitdb/platforms/windows/local/271.c .

Move back to parent directory:

cd ..

OS info:

uname -a
(Debian 4.6.4-1kali1)

What have i tried?

I found it simple enough to create the directories...

for fldr in $(cat list.txt); do mkdir -p $fldr; done

...but unsure of the best way to use cut and assign to variables etc. It would be great to learn experienced Linux users approach this.

Asked April 21, 2017
Posted Under: Unix Linux
1 Answers

Try this, and if it needs refinement, let me know :

while read line; 
  mkdir -p "${line}"
  prefix=`echo "${line}" | cut -d'_' -f1`
  find /usr/share/exploitdb/ -name  "${prefix}".* -exec echo {} "${line}/" \;
done < list.txt

Replace the echo with cp from the find if the command output seems ok to you.

Answered April 21, 2017
work nicely, thanks for the help :-) – ade1e 10 mins ago
 CanDoerz  1 year ago
Instead of using the prefix variable you could leave away the fourth line and directly use ${line%%_*} to remove everything after the _, at least in zsh and bash. – Philippos 17 mins ago
 CanDoerz  1 year ago
Your Answer