如何只列出目录名称,不带尾部“ /”?

问题描述

通过在文件夹中执行以下命令

ls -d */ | cut -f1 -d'/'

我得到如下条目:

env1
env2
env3
env4

如何使用cat/grepyq/jq或任何其他替代命令代替上述命令?

解决方法

for dir in */; do
  echo "${dir%/}"
done
,

有几种选择。您可以将tree命令与以下选项一起使用:

# d: list only directories
# i: no print of indention line
# L: max display depth of the directory tree
tree -di -L 1 "$(pwd)"

或者您也可以使用grep命令获取目录和命令awk

# F: input field separator
# $9: print the ninth column of the output
ls -l | grep "^d" | awk -F" " '{print $9}' 

或者您可以使用sed命令删除斜杠:

# structure: s|regexp|replacement|flags
# g: apply the replacement to all matches to the regexp,not just the first
ls -d */ | sed 's|[/]||g'

我在此post中找到了这种解决方案。