William William - 13 days ago 5
Bash Question

Bash - Moving files using destination from txt file

I have a text file (log.txt) containing a list of file paths where I want files to end up.

/root/NewDir/Testfile.txt
/root/NewDir/Testfile2.txt
/root/NewDir2/Alsoatest.txt
...


The files are currently sat in the same location as log.txt

/root/Dustbin/log.txt
/root/Dustbin/Testfile.txt
/root/Dustbin/Testfile2.txt
/root/Dustbin/Alsoatest.txt
...


I am trying to create a script that can take just the filename and will move the specified file to the location stated in the log.txt file.

For example:

# restore Testfile.txt


The result should be Testfile.txt moving from /root/Dustbin/... to /root/NewDir/...

I am a total newbie at bash / shellscript and have tried researching this for hours but am totally stumped!
I know I need to use the 'mv' function but am not sure how to populate the destination with those specified in the log.txt file by matching the filenames!

Would anyone have any idea or be able to point me in the right direction?

Answer

Try with:

#!/bin/bash 

dustbin="/root/Dustbin"
file="$1"

mv $dustbin/$file $(egrep "\/$file$" $dustbin/log.txt)

Depending of your requirements, you could improve the script adding a "mkdir" before the "mv", ... .

Comments