Search code examples
linuxbashshellbioinformatics

How do I loop through mgz files and convert them to nii files using a shell script and freesurfer?


I need to automate converting mgz files into nii files using freesurfer. I have tried a number of different tactics, but for some reason my script wont loop through the files and they can't be read. It isn't a permission problem because I can do other commands on the files.

I have created a shell script that prompts the user for the file path for whichever folder the files are stored in. When I run it, it says "mri_convert: missing output volume name type mri_convert -u for usage".

Here is my script with the loop:

#!/bin/bash 

#ask user for filepath - Works 
read -p "Enter filepath: " fp 

#confirm filepath - Works 
read -p "Continue? You said ${fp} (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1 

#loop through files 
for FILE in "${fp}/*" 
do 
        #seperate file extentsion and name 
        filepath=$fp$FILE 
        filename_with_ext=$(basename $filepath) 
        filename="${filename_with_ext%.*}" 
        extension="${filename_with_ext##*.}" 

        #concatinate filename with new extension         
        ni_file="${filename}.nii" 
  
        #convert to nii using now seperated file name concaqtinated with .nii 
        mri_convert ${FILE} ${ni_file} 

done 

I'd like the script to ask the user for the filepath to the folder containing all the files. Then I want to loop through that folder and with each file I want to get the individual file name with the original file extension and the file name with the nii file extension. I am trying to do this by separating the file name from its original extension and then concatenating the file name with .nii. Finally I want to call mri_convert on the file by using its original name and file extensions and then the target file name with the nii extension.


Solution

  • Thanks for all the help. I ended up with this script and it's working beautifully!

    #!/bin/bash 
    #ask user for filepath and change directory to filepath 
    read -p "Enter filepath: " fp  
    cd "$fp" 
    
    #loop through files 
    for file in * 
    do 
            #seperate file extentsion and name 
            filepath="${fp}${file}" 
            filename_with_ext=$(basename "$filepath") 
            filename="${filename_with_ext%.*}" 
            extension="${filename_with_ext##*.}" 
    
            #concatinate filename with new extension         
            ni_file="${filename}.nii" 
    
            #convert to nii using now seperated file name concaqtinated with .nii 
            mri_convert --in_type mgz --out_type nii "${file}" "${ni_file}" 
    done