简体   繁体   中英

copy multiple files from directory tree to new different tree; bash script

I want to write a script that do specific thing:

I have a txt file eg

from1/from2/from3/apple.file;/to1/to2/to3;some not important stuff
from1/from2/banana.file;/to1/to5;some not important stuff
from1/from10/plum.file;/to1//to5/to100;some not important stuff

Now i want to copy file from each line (eg apple.file), from original directory tree to new, non existing directories, after first semicolon (;).

I try few code examples from similar questions, but nothing works fine and I'm too weak in bash scripting, to find errors. Please help :)

need to add some conditions: file not only need to be copy, but also rename. Example line in file.txt:

from1/from2/from3/apple.file;to1/to2/to3/juice.file;some1
from1/from2/banana.file;to1/to5/fresh.file;something different from above

so apple.file need to be copy and rename to juice.file and put in to1/to2/to3/juice.file I think thaht cp will also rename file but

mkdir -p "$to"

from answer below will create full folder path with juice.file as folder

In addidtion after second semicolon in each line will be something different, so how to cut it off? Thanks for all help

EDIT: There will be no spaces in input txt file.

Try this code..

cat file | while IFS=';' read from to some_not_important_stuff
  do
    to=${to:1}  # strip off leading space
    mkdir -p "$to"  # create parent for 'to' if not existing yet
    cp -i "$from" "$to"  # option -i to get a warning when it would overwrite something
  done

Using awk

(run the awk command first and confirm the output is fine, then add |sh to do the copy)

awk -F";" '{printf "cp %s %s\n",$1,$2}' file |sh

Using shell (get updated that need manually create folder, base on alfe's

while IFS=';' read from to X
do
    mkdir -p $to
    cp $from $to 
done < file

I had this same problem and used tar to solve it! Posted here :

tmpfile=/tmp/myfile.tar
files="/some/folder/file1.txt /some/other/folder/file2.txt"
targetfolder=/home/you/somefolder

tar --file="$tmpfile" "$files"​
tar --extract --file="$tmpfile" --directory="$targetfolder"

In this case, tar will automatically create all (sub)folders for you! Best,

Nabi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM