簡體   English   中英

將多個文件從目錄樹復制到新的不同樹; bash 腳本

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

我想編寫一個執行特定操作的腳本:

我有一個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

現在我想將文件從每一行(例如 apple.file),從原始目錄樹復制到新的、不存在的目錄,在第一個分號 (;) 之后。

我嘗試了一些來自類似問題的代碼示例,但沒有任何效果,而且我在 bash 腳本方面太弱,無法找到錯誤。 請幫忙 :)

需要添加一些條件:文件不僅需要復制,還需要重命名。 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

所以apple.file需要復制並重命名為juice.file並放入to1/to2/to3/juice.file我認為cp也會重命名文件但是

mkdir -p "$to"

從下面的答案將使用juice.file作為文件夾創建完整的文件夾路徑

此外,每行第二個分號后的內容會有所不同,那么如何將其截斷? 感謝所有幫助

編輯:輸入 txt 文件中將沒有空格。

試試這個代碼..

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

使用 awk

(先運行 awk 命令確認輸出正常,然后添加|sh進行復制)

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

使用 shell(獲取需要手動創建文件夾的更新,基於 alfe 的

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

我遇到了同樣的問題,並使用tar來解決它! 在這里發布:

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"

在這種情況下, tar會自動為您創建所有(子)文件夾! 最好的事物,

娜比

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM