Skip to content
Advertisement

Linux: Loop using foldername when finding file

I’m currently trying to use the following linux script to loop through folders and perform calculations using a function:

for f in s*
do
    echo "You are in the following folder - $s" 
    cd $s

    # FUNCTION SHOULD BE HERE

    cd /C/Users/Eric/Desktop/Files
done

The problem: How can I use the foldername to find the correct file? For example, the foldername is scan1 and I want to use the file called gaf_scan1_recording_mic.nii for the function.

Thanks a lot,

Eric

Advertisement

Answer

In most cases, $var and ${var} are the same (the braces are only needed for ambiguity in the expressions):

var=test
echo $var
# test
echo ${var}
# test
echo $varworks
# prints nothing (there is no variable 'varworks')
echo ${var}works
# testworks

You can use the folder name like this (gaf_${f}_recording_mic.nii):

for f in *; do
    # Check if $f is a directory
    if [[ -d $f ]]; then
        echo "You are in the following folder - $f" 
        cd $f
        # The filename to use for your function
        do_stuff gaf_${f}_recording_mic.nii
    fi
done
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement