BASH:将find命令的值打印到特定点并分配给变量

时间:2019-12-27 10:14:48

标签: bash scripting

我试图通过2个步骤定义变量-

$ find /u01/app -name cmd_history.txt

返回类似(例如)

  

/u01/app/refresh/db/18c/test/etc/cmd_history.txt

$ export WORK_DIR=/u01/app/refresh/db/18c/test/etc(/ cmd_history.txt除外)

基本上,我想在1个命令中实现此目标,即将find的输出提供给awk或剪切并忽略/cmd_history.txt。

$ export WORK_DIR=find /u01/app -name cmd_history.txt | awk or cut 

我该如何实现?

2 个答案:

答案 0 :(得分:0)

这是不需要awk或cut的解决方案:

WORK_DIR=$(find /u01/app -name cmd_history.txt)
export WORK_DIR=${WORK_DIR%/*}

$ {WORK_DIR%/ *}删除最后一部分:/cmd_history.txt

这是一个更简单的解决方案:

export WORK_DIR=$(find /u01/app -name cmd_history.txt -printf %h)

其中 -printf%h 直接给出目录。

答案 1 :(得分:0)

使用GNU find

您可以使用-printf '%h'打印开头的目录,并在与find进行第一次匹配后退出-quit

export WORK_DIR=$(find /u01/app -name 'cmd_history.txt' -printf '%h' -quit)

使用BSD find

打印第一个匹配项,然后退出并使用dirname获取父目录。

export WORK_DIR=$(dirname "$(find /u01/app -name 'cmd_history.txt' -print -quit)")
相关问题