【问题标题】:Find list of directories as comma separated string, with no trailing comma以逗号分隔的字符串形式查找目录列表,没有尾随逗号
【发布时间】:2018-09-03 17:21:51
【问题描述】:

我正在尝试生成目录列表,以逗号分隔的字符串形式

find . -type d -mindepth 1 | tr '\n' ','

这给了我一个带有尾随逗号的字符串。

dirA,dirB,dirc,

我知道我可以添加 sed 或 awk 来去除尾随逗号,但有没有办法构造 findtr 来完成此操作?

【问题讨论】:

    标签: bash find comma tr


    【解决方案1】:

    不使用tr,但一个简单的解决方案可能是使用paste

    find . -type d -mindepth 1 | paste -sd,
    

    【讨论】:

    • 不确定这是否是 macos 的东西,但我必须添加一个额外的连字符才能使其工作:find . -type d | paste -sd , -。选择这个,因为它看起来更简单
    【解决方案2】:

    您可以使用parameter expansion 去掉多余的,

    list=$(find . -mindepth 1 -type d -printf '%p,'); echo "${list%,}" 
    

    即使对于带有换行符的文件名,这也能正常工作。

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多