Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get directory and file names while looping in shell script [duplicate]

Tags:

linux

bash

shell

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?

like image 571
nexita Avatar asked Nov 30 '25 02:11

nexita


1 Answers

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
like image 150
Juan Diego Godoy Robles Avatar answered Dec 02 '25 18:12

Juan Diego Godoy Robles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!