bash / find :查找位于上述目录中的文件

问题描述 投票:0回答:3

以下脚本尝试搜索与模式匹配的文件并将它们复制到当前目录。

# pattern to search
lig="lig*"
output=$(pwd)
# find in anywhere and copy to the current dir
find -maxdepth 1 ../../ -name "${lig}*.png" -exec cp "{}" ${output}  \;

在我的情况下,我需要在当前目录上方的某个位置查找

$lig
,即

/home/user/Bureau/Analyse/BCL_MDtest_haddock2/Analysis

并且

lig*
文件位于

/home/user/Bureau/Analyse/BCL_MDtest_haddock2/!plots

由于我没有考虑当前目录中所有包含的子文件夹,因此如何在当前文件夹上方定义

find
的搜索空间(与最大深度相反)?

bash find
3个回答
1
投票

如何定义当前文件夹上方查找的搜索空间(与最大深度相反)

find
只能搜索以给定起点为根的目录树。它不能从那里向上。然后,如果您尝试提供足够高的根目录(例如
../../
),并从那里向下遍历到当前目录(使用相应的
-maxdepth 2
),则需要主动排除所有恰好共享该目录的不需要的同级路径root 作为共同祖先,在我看来,这是不必要的低效且不值得付出努力。

相反,如果您只想从某些上层目录复制一些文件,为什么不直接使用一个精心设计的

cp
命令来完成呢?如果需要,可以通过设置 shell 选项来避免与不包含具有该模式的文件的目录相关的错误:
shopt -s nullglob
(使用
-u
再次取消设置)。

cp {..,../..}/lig*.png ./
#   ..                      first directory as one source directory
#      ../..                second directory as another source directory
#             lig*.png      filename pattern in the source directories
#                      ./   current directory as the target directory

如果这对您的用例来说限制太多(父目录的静态数量、必须列出所有中间目录、命令长度限制等)和/或您希望更多地控制每个文件的处理方式,您也可以首先动态地循环遍历连续的父目录,然后遍历它们匹配的各个文件,并逐一处理它们来编写脚本:

pattern="lig*.png"
updirs=2

intodir="$PWD"
while [[ $((--updirs)) -ge 0 ]]; do
  cd ..
  for file in $pattern; do
    [[ -e "./$file" ]] && cp "./$file" "$intodir"
  done
done
# cd "$intodir" # if you need to come back within the script

0
投票

不确定我是否真的理解用例,但对于“通用”部分,我认为您可能想考虑使用

dirname
命令。它基本上返回路径的目录(在本例中为父目录)。 例如,您可以执行
find "$(dirname $PWD)"
... 基本上从父目录中搜索。


0
投票

根据您的评论

我正在寻找当前解决方案的替代方案,该解决方案在技术上 有效,但不能通用

在我的场景中,

$(dirname "$(pwd)")
用于动态获取当前目录的父目录,然后使用
-path
在与模式
${lig}*.png
匹配的任何子目录中搜索与模式(
*/
)匹配的文件,这意味着当前目录之上的任何目录!

让我告诉你如何做:

#pattern to search
lig="lig*"
output=$(pwd)

#find in directories above the current directory and copy to the current directory
find "$(dirname "$(pwd)")" -path "*/${lig}*.png" -exec cp "{}" "${output}" \;
© www.soinside.com 2019 - 2024. All rights reserved.