2

I'm doing a loop in files of directories and I need to get the current directory and file name on each step.

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

I also need the file name without the extension ( .ext ). How should I make it?

nexita
  • 35
  • 1
  • 6

2 Answers2

4

You can use basename and dirname:

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

Another way using awk with .ext deletion:

for f in /path/to/*/*.ext ;do
   echo "$f"|awk -F\/ '{a=$NF;$NF="";gsub(".ext","",a)}{print $0" "a}' OFS=\/
done
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
2

In Bash, use the following:

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

See Shell Parameter Expansion.

The shopt -s nullglob is highly recommended, so that the glob /path/to/*/*.ext expands to nothing (and hence the loop is not executed, so that my_command is not executed with the random verbatim arguments /path/to/* and *.ext) if there are no matches.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104