Unix“查找"命令用法 [英] Unix "find" command usage

查看:19
本文介绍了Unix“查找"命令用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个 bash 安装脚本.脚本 foo.sh 将DIRECTORY"作为参数.比如说,有一个目录 <$HOME>/TEST/TEST_1A/TEST_2A/TEST_3 和另一个目录 <$HOME>/TEST/TEST_1B/TEST_2B/TEST_3.

This is for a bash installation script. The script foo.sh takes "DIRECTORY" as an argument. Say, there is a dir <$HOME>/TEST/TEST_1A/TEST_2A/TEST_3 and another dir <$HOME>/TEST/TEST_1B/TEST_2B/TEST_3.

脚本:foo.sh 简介.

Script: foo.sh in brief.

DIR='find $HOME -type d -name $1 | head 1'
if [ DIR is set to a directory ]
then
   rm -rf $DIR
fi
exit 0

用法:foo.sh TEST_3

现在从脚本中,只能删除 <$HOME>/TEST/TEST_1A/TEST_2A/TEST_3.要删除 <$HOME>/TEST/TEST_1B/TEST_2B/TEST_3,我需要在我的 find 命令中使用 reg exp 来微调删除以解决目录冲突.

Now from the script, only the <$HOME>/TEST/TEST_1A/TEST_2A/TEST_3 can be removed. To remove <$HOME>/TEST/TEST_1B/TEST_2B/TEST_3, I need to use a reg exp in my find command, to fine tune the remove to resolve the directory conflict.

将上述脚本的查找部分修改如下

Modified the find part of the above script as below

DIR='find $HOME -type d -regexp $1 | head 1'

新用法:foo.sh TEST_2B/TEST_3

但查找"命令无法将 DIR 设置为 <$HOME>/TEST/TEST_1B/TEST_2B/TEST_3 而是返回空 &结果 DIR 为空,我永远无法删除 <$HOME>/TEST/TEST_1B/TEST_2B/TEST_3

But "find" command FAILS to get the DIR set to <$HOME>/TEST/TEST_1B/TEST_2B/TEST_3 and instead returns empty & as a result DIR is empty and I can never ever remove <$HOME>/TEST/TEST_1B/TEST_2B/TEST_3

如何更改脚本,以便 find 可以仅对目录名称以及目录路径进行操作,而不会出现任何问题.事实上,一些用户可能会将部分目录路径作为foo.sh"的参数.我希望foo.sh"能够工作,即使在这种情况下

How do I change the script, so that find can act on JUST the directory name, as well as on the path to the directory too with NO issues. Infact, some users may give a partial directory path as argument to "foo.sh". I expect "foo.sh" to work, even in such cases

推荐答案

你可以试试:

if [[ "$1" == */* ]]; then
    EXPR="-path *$1"
else
    EXPR="-name $1"
fi
DIR=$(find $HOME -type d $EXPR | head -1)

像TEST_3"这样的简单名称将转换为find -name TEST_3,但像ST_2/TEST_3"这样带有斜线的名称将转换为find -path *ST_2/TEST3.这将处理(部分)目录名称.

A simple name like "TEST_3" will translate into find -name TEST_3 but a name with a slash like "ST_2/TEST_3" will translate into find -path *ST_2/TEST3. This will take care of (partial) directory names.

这篇关于Unix“查找"命令用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆