0

I am trying to rename nifti files, aiming to keep the first 15 characters of filename (which are random and indicate subject id) and rename the rest of the file to "scan_name.nii.gz"?

for i in `ls ${dir}/nifti_loc`; do echo ${i};  
for j in `ls ${dir}/nifti_loc/*MPRAGE*.nii.gz | grep -v -i AXI`; do   
cp ${j} ${dir}/nifti_loc/rename/${j}\_mprage.nii.gz;  
done;  
done;
jared_mamrot
  • 22,354
  • 4
  • 21
  • 46
  • You can refer to the answers of this question: https://stackoverflow.com/questions/71732150/delete-every-number-after-14-digit-count – Roozbeh Sayadi Apr 06 '22 at 05:17
  • 1
    ***Never*** use `for i in $(ls anything)`, see [**Bash Pitfalls #1**](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29) (there is a reason that is pitfall **#1**). Instead, e.g. `for i in ${dir}/nifti_loc/*; do ...` Also, your nested loop will invoke the inner loop once **for every file** in `${dir}/nifti_loc`. Why not just use your `j` loop? – David C. Rankin Apr 06 '22 at 06:14

1 Answers1

1

Does this provide your expected outcome?

cd "${dir}"/nifti_loc

for f in *MPRAGE*.nii.gz
do
    mv "$f" "${f:0:15}_scan_name.nii.gz"
done
jared_mamrot
  • 22,354
  • 4
  • 21
  • 46
  • You have a *good* answer. It would be a *better* answer if you explained what `${f:0:15}` is? (parameter expansion for *substring expansion* of `${parameter:offset:length}`) and how it solves the problem). *Code-Only* answers are usually not helpful for others who may land on this question later. A couple of sentences is all you need. That said, I'll give you the nod for the *good* solution with hope in the future they become *better*. – David C. Rankin Apr 06 '22 at 06:18