1

I am trying to print the file names that are including the extension of (.gz) in directory. currently i have the below shell script which is printing the absolute path. I want to print only the file name.

can someone advise on this. I have tried different ways.

#!/bin/bash

sourceFolder=/Users/rojadhanavath/Desktop/app/logs/*.gz

sleepTimeinMinutes=200

cd $sourceFolder

for f in $sourceFolder do
   echo " printing the file name $f" done

the current output is :

printing the file name
/Users/rojadhanavath/Desktop/app/logs/app-json.log copy 10.gz 
printing the file name
/Users/rojadhanavath/Desktop/app/logs/app-json.log copy 11.gz 
printing the file name
/Users/rojadhanavath/Desktop/app/logs/app-json.log copy 12.gz 
printing the file name
/Users/rojadhanavath/Desktop/app/logs/app-json.log copy 2.gz  printing
the file name /Users/rojadhanavath/Desktop/app/logs/app-json.log copy
3.gz

I want only the file name:

e.g. app-json.log copy 10.gz

2
  • You don't need to cd to the folder since you've already declared a full path. Incidentally, it's better to use cd "$folder" || exit, and in the loop quote the variable:"$sourceFolder". and sourceFolder="/Users/rojadhanavath/Desktop/app/logs/*.gz" and cd "$sourceFolder" Oct 2, 2020 at 16:28
  • 1
    It's probable there's an error message from cd that you haven't shown us, above the printing the file name loop
    – roaima
    Oct 2, 2020 at 16:29

3 Answers 3

3

You can take the basename of $f:

for f in $sourceFolder; do
    echo " printing the file name $(basename $f)"
done

or, since you already used cd $sourceFolder, this will work as well:

for f in *.gz; do
    echo " printing the file name $f"
done
2
  • thank you for the response. i was running this script on a server- the issue was related to specific server and i have update apt package and it worked.
    – Roja
    Oct 3, 2020 at 17:26
  • No problem. You can click the checkmark on an answer to accept it as the solution.
    – laktak
    Oct 3, 2020 at 18:46
0

The appropriate answer is @laktak. But here there's another approach:

for f in "$sourceFolder"; do 
  echo " printing the file name ${f##*/}"
done
2
  • I think that might want to be "${f##*/}". The wildcard applies to the directory name -- i.e. everything before the last / Oct 2, 2020 at 16:11
  • @Paul_Pedant Yes! I misplaced the wildcard. Oct 2, 2020 at 16:17
0

The file-extension part is easy. There is no such thing. There are some tools that will help you work with this concept (e.g. basename), but they don't exist, so just ignore it. For what you need use the tool dirname.

e.g.

echo " printing the file name $(dirname "$f")"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.