[英]copy files with the base directory
我正在搜索特定目錄和子目錄中的新文件,我想復制這些文件。 我正在使用這個:
find /home/foo/hint/ -type f -mtime -2 -exec cp '{}' ~/new/ \;
它成功復制了文件,但是某些文件在/home/foo/hint/
不同子目錄中具有相同的名稱。 我想將文件及其基本目錄復制到~/new/
目錄。
test@serv> find /home/foo/hint/ -type f -mtime -2 -exec ls '{}' \;
/home/foo/hint/do/pass/file.txt
/home/foo/hint/fit/file.txt
test@serv>
~/new/
復制后應如下所示:
test@serv> ls -R ~/new/
/home/test/new/pass/:
file.txt
/home/test/new/fit/:
file.txt
test@serv>
平台:Solaris 10。
由於不能使用rsync或高級GNU選項,因此需要使用Shell自己滾動。
使用find
命令可以在-exec
運行完整的外殼程序,因此最好使用單行處理名稱。
如果我理解正確,則只希望將父目錄而不是完整樹復制到目標。 以下可能會做:
#!/usr/bin/env bash
findopts=(
-type f
-mtime -2
-exec bash -c 'd="${0%/*}"; d="${d##*/}"; mkdir -p "$1/$d"; cp -v "$0" "$1/$d/"' {} ./new \;
)
find /home/foo/hint/ "${findopts[@]}"
結果:
$ find ./hint -type f -print
./hint/foo/slurm/file.txt
./hint/foo/file.txt
./hint/bar/file.txt
$ ./doit
./hint/foo/slurm/file.txt -> ./new/slurm/file.txt
./hint/foo/file.txt -> ./new/foo/file.txt
./hint/bar/file.txt -> ./new/bar/file.txt
我將要find
的選項放入bash數組中,以便於閱讀和管理。 -exec
選項的腳本仍然有些笨拙,因此下面是每個文件的功能細目。 請記住,以這種格式,選項從零開始編號, {}
變為$0
,目標目錄變為$1
...
d="${0%/*}" # Store the source directory in a variable, then
d="${d##*/}" # strip everything up to the last slash, leaving the parent.
mkdir -p "$1/$d" # create the target directory if it doesn't already exist,
cp "$0" "$1/$d/" # then copy the file to it.
我使用了cp -v
進行詳細輸出,如上面的“結果”所示,但是IIRC也不被Solaris支持,可以安全地忽略它。
--parents
標志應該可以解決問題:
find /home/foo/hint/ -type f -mtime -2 -exec cp --parents '{}' ~/new/ \;
嘗試使用rsync -R
進行測試,例如:
find /your/path -type f -mtime -2 -exec rsync -R '{}' ~/new/ \;
從rsync男子:
-R, --relative
Use relative paths. This means that the full path names specified on the
command line are sent to the server rather than just the last parts of the
filenames.
@Mureinik和@nbari回答的問題可能是新文件的絕對路徑將在目標目錄中產生。 在這種情況下,您可能想在命令之前切換到基本目錄,然后再返回到當前目錄:
path_current=$PWD; cd /home/foo/hint/; find . -type f -mtime -2 -exec cp --parents '{}' ~/new/ \; ; cd $path_current
要么
path_current=$PWD; cd /home/foo/hint/; find . -type f -mtime -2 -exec rsync -R '{}' ~/new/ \; ; cd $path_current
在Linux平台上,兩種方式都對我有效。 希望Solaris 10知道rsync的-R! ;)
我找到了解決方法:
cd ~/new/
find /home/foo/hint/ -type f -mtime -2 -exec nawk -v f={} '{n=split(FILENAME, a, "/");j= a[n-1];system("mkdir -p "j"");system("cp "f" "j""); exit}' {} \;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.