[英]Using bash command to copy files from a subfolder to another
我有以下結構:
.
├── dag_1
│ ├── dag
│ │ ├── current
│ │ └── deprecated
│ └── sparkjobs
│ ├── current
│ | └── spark_3.py
│ └── deprecated
│ └── spark_1.py
│ └── spark_2.py
├── dag_2
│ ├── dag
│ │ ├── current
│ │ └── deprecated
│ └── sparkjobs
│ ├── current
│ | └── spark_3.py
│ └── deprecated
│ └── spark_1.py
│ └── spark_2.py
我想創建一個僅獲取當前 spark 作業的新文件夾,我預期的 output 文件夾是:
.
├── dag_1
| └── spark_3.py
├── dag_2
└── spark_3.py
我試過使用
find /mnt/c/Users/User/Test/ -type f -wholename "sparkjob/current" | xargs -i cp {} /mnt/c/Users/User/Test/output/
盡管我的腳本沒有寫入文件並且沒有返回任何錯誤。 我該如何解決這個問題?
使用這個, install
命令獲取輸入文件並將其復制到另一個目錄結構,必要時創建整個目錄樹作為mkdir -p
透明地:
(需要在-wholename
中加通配符*
才能有效查找文件)
find . -type f -wholename "*/sparkjob/current/*" -exec bash -c '
dir=${1#./} dir=${dir%%/*} file=${1##*/}
install -D "$1" "./$dir/$file"
' bash {} \;
install -D ./dag_2/sparkjob/current/spark_3.py ./dag_2/spark_3.py
install -D ./dag_1/sparkjob/current/spark_3.py ./dag_1/spark_3.py
源路徑是一個例子,如果更長,沒問題。
我想你正在尋找這樣的東西:
cd /mnt/c/Users/User/Test
for src in ./*/sparkjobs/current; do
dest=output/${src%/*/*}
echo cp -R "$src" "$dest"
done
如果 output 看起來不錯,則丟棄echo
。
你會想要做的:
mkdir ../new_folder
find . -type f \
-path '*/sparkjobs/current/*' \
-exec sh -c 'f=$1
new=${f/sparkjobs\/current\//}
dest="../new_folder/$(dirname "$new")"
mkdir -p "$dest"
cp -v "$f" "$dest"' sh '{}' \;
‘./dag_1/sparkjobs/current/spark_3.py’ -> ‘../new_folder/./dag_1/spark_3.py’
‘./dag_2/sparkjobs/current/spark_3.py’ -> ‘../new_folder/./dag_2/spark_3.py’
首先,您應該通過刪除|
之后的所有內容來檢查find
返回的內容 . 你會看到find
沒有找到任何文件。 原因:
-wholename
匹配全名,所以需要*/sparkjob/current/*
tree
output,該文件夾未命名為sparkjob
而是sparkjobs
。我會從這樣的事情開始:
find /mnt/c/Users/User/Test/ -type f -wholename "*/sparkjobs/current/*" -print0 | while IFS= read -r -d '' file; do
echo mv "$file" "$(realpath "$(dirname "$file")"/../..)"
done
我添加了一個echo
,這樣你就可以檢查所有路徑和命令是否正確。
您可能希望以簡單性換取性能。 如果性能很重要(許多文件或頻繁運行),請參閱https://mywiki.wooledge.org/BashFAQ/001 。
這看起來很簡單。
for d in $old_loc/dag_*
do mkdir -p "$new_loc/${d##*/}"
cp "$d"/sparkjobs/current/spark_*.py "${d##*/}"
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.