我正在做目录文件中的循环,我需要在每个步骤中获取当前目录和文件名。如何在shell脚本中循环时获取目录和文件名
for f in /path/to/*/*.ext
do
command "$d" "f" #! Here we send those two as parameters
done
我还需要没有扩展名(.ext)的文件名。我应该怎么做?
我正在做目录文件中的循环,我需要在每个步骤中获取当前目录和文件名。如何在shell脚本中循环时获取目录和文件名
for f in /path/to/*/*.ext
do
command "$d" "f" #! Here we send those two as parameters
done
我还需要没有扩展名(.ext)的文件名。我应该怎么做?
您可以使用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
在bash,使用以下命令:
shopt -s nullglob
for f in /path/to/*/*.ext; do
my_command "${f%/*}" "${f##*/}"
done
的shopt -s nullglob
强烈建议,使水珠/path/to/*/*.ext
什么也不扩展(因此循环不执行,让my_command
不与随机逐字参数/path/to/*
和*.ext
执行),如果没有匹配。