在 AIX 中使用 shell 脚本打印所有 3 个字符的子目录

在 AIX 中使用 shell 脚本打印所有 3 个字符的子目录

在我的系统中,有一个/Test目录,该目录下有很多目录。我想打印 AIX 系统中所有具有 3 个字符名称的目录。

我得到了 Gnu/Linux 的代码。

find /test -maxdepth 1 -type d | awk -F / 'length($NF) == 3' |awk -F / '{print $3} ' 

这是一个 AIX 服务器。

ex : /test 目录包含子目录

test1
AAA
BBB
Test2
test3

所需输出:

AAA
BBB

答案1

将 POSIX 查找限制到特定深度?findGNU谓词的标准等效项-maxdepth。所以在这里:

(cd /Test && find . ! -name . -prune -type d -name '???') | sed 's|\./||'

或者如果zsh安装了:

zsh -c 'printf "%s\n" /Test/???(D/:t)'

答案2

一个简单的 shell 循环解决方案是

for pathname in Test/???/; do
    printf '%s\n' "$( basename "$pathname" )"
done

这将打印与给定模式匹配的每个子目录名称(或子目录的符号链接的名称)。

如果你想做除此之外的任何事情清单名字,那么你会做类似的事情

for pathname in Test/???/; do
    # some code using "$pathname" here
done

即,你会不是首先生成列表,然后对其进行迭代。

答案3

鉴于您不想递归到目录中,一个简单的通配符可以够了。基线是???/,意思是“匹配恰好包含三个字符的目录名称;在 ksh 的默认 AIX shell 中,您需要添加.??/以匹配以句点开头并后跟两个字符的“隐藏”目录(假设您计算句号作为三个之一;.???/如果句号不算数,则使用)。

除此之外,唯一的“技巧”是:

  • 使用子 shellcd进入 /test 目录;否则,您需要另外对前导“/test”字符串进行后处理。

  • 由于我们使用尾部斜杠/来强制通配符匹配目录(与文件),因此我们使用sed从每行中删除尾部斜杠。

那么单行是:

(cd /test; printf '%s\n' ???/ .??/) | sed 's!/$!!'

示例设置如下:

mkdir /test
mkdir /test/AAA /test/BBB /test/.AB
touch /test/aaa

样本结果为:

AAA
BBB
.AB

相关内容