简体   繁体   English

将多个文件从目录树复制到新的不同树; bash 脚本

[英]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我有一个txt文件,例如

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 (;).现在我想将文件从每一行(例如 apple.file),从原始目录树复制到新的、不存在的目录,在第一个分号 (;) 之后。

I try few code examples from similar questions, but nothing works fine and I'm too weak in bash scripting, to find errors.我尝试了一些来自类似问题的代码示例,但没有任何效果,而且我在 bash 脚本方面太弱,无法找到错误。 Please help :)请帮忙 :)

need to add some conditions: file not only need to be copy, but also rename.需要添加一些条件:文件不仅需要复制,还需要重命名。 Example line in file.txt: 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所以apple.file需要复制并重命名为juice.file并放入to1/to2/to3/juice.file我认为cp也会重命名文件但是

mkdir -p "$to"

from answer below will create full folder path with juice.file as folder从下面的答案将使用juice.file作为文件夹创建完整的文件夹路径

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.编辑:输入 txt 文件中将没有空格。

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使用 awk

(run the awk command first and confirm the output is fine, then add |sh to do the copy) (先运行 awk 命令确认输出正常,然后添加|sh进行复制)

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

Using shell (get updated that need manually create folder, base on alfe's使用 shell(获取需要手动创建文件夹的更新,基于 alfe 的

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!我遇到了同样的问题,并使用tar来解决它! 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!在这种情况下, tar会自动为您创建所有(子)文件夹! Best,最好的事物,

Nabi娜比

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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