Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get only file name in variable in a for loop

I have a for loop that writes text in a file :

for f in $DATA_DIRECTORY 
do 
    echo ' input.'$f '{'
    echo '  copy = ${source.copy}"'$f'.CPY"'
    echo '  data = ${source.data}"'$f'.CSV"'
    echo ' }'
done

But the "f" variable here looks like this :

/path/to/my/file/FILE.TXT

What i want to get is only the name of the file, not the full path and its extension:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

FILE

By the way i tried to change my f variable like this so i dont get the extension but it did not work :

{$f%%.*}

>Solution :

You need two lines; chained operators aren’t allowed.

f=${f##*/}  # Strip the directory
f=${f%%.*}  # Strip the extensions

Or, you can use the basename command to strip the directory and one extension (assuming you know what it is) in one line.

f=$(basename "$f" .txt)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading