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

问题描述

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

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中找到了这种解决方案。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...