【问题标题】:How to get directory and file names while looping in shell script [duplicate]如何在shell脚本中循环时获取目录和文件名[重复]
【发布时间】:2015-04-10 11:29:19
【问题描述】:

我正在目录文件中循环,我需要在每个步骤中获取当前目录和文件名。

for f in /path/to/*/*.ext
do
  command "$d" "f" #! Here we send those two as parameters
done

我还需要不带扩展名的文件名 ( .ext )。我该怎么做呢?

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    您可以使用basename 和dirname:

    for f in /path/to/*/*.ext
    do
      command "$(dirname "$f")" "$(basename "$f")" 
    done
    

    使用awk 删除.ext 的另一种方式:

    for f in /path/to/*/*.ext ;do
       echo "$f"|awk -F\/ '{a=$NF;$NF="";gsub(".ext","",a)}{print $0" "a}' OFS=\/
    done
    

    【讨论】:

      【解决方案2】:

      在 Bash 中,使用以下内容:

      shopt -s nullglob
      for f in /path/to/*/*.ext; do
          my_command "${f%/*}" "${f##*/}"
      done
      

      见Shell Parameter Expansion。

      强烈建议使用shopt -s nullglob,以便全局/path/to/*/*.ext 扩展为空(因此不会执行循环,因此不会使用随机逐字参数/path/to/* 和*.ext 执行my_command ) 如果没有匹配项。

      【讨论】:

        猜你喜欢
        • 2021-02-08
        • 2013-10-06
        • 2017-03-26
        • 2015-05-24
        • 2017-04-09
        • 1970-01-01
        • 2021-06-25
        • 2014-11-18
        • 2012-09-09
        相关资源
        最近更新 更多